Skip to main content
gamedev.net
🔒 Locked

Setting precision on float text.

Started by Roof Top Pew Wee Feb 3, 2004 at 1:02 AM 0 replies 200+ views
Original Post
Roof Top Pew Wee
Roof Top Pew Wee
Say I have a float and I want to convert it to text, but when I do, I want to have a set precision (number of digits past the decimal). I was thinking something like this: // defined and declared precision before hand int multiple = 1; for(int i = 0; i < precision; i++) multiple*= 10; int tempInt = floatToConvert*multiple; float convertedFloat = (float)tempInt/(float)multiple; string finalText = convertedFloat.ToString(); Of course, I''m using C# on this. I think this will work. That is, at least I''m passing on the logic, even if there are some bugs. Is there a way to do this that is faster? --Vic--
SiCrane
SiCrane
I think it would just be easier to use System.Globalization.NumberFormatInfo.
ex:

double number = 500.12345;
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
nfi.NumberDecimalDigits = 4;
Console.WriteLine(number.ToString( "N", nfi ));

Or if the number of digits is fixed at compile time, just use a formatting string.

Console.WriteLine(System.String.Format("{0:0.0000}", number));

edit: formatting

[edited by - SiCrane on February 3, 2004 2:22:35 AM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.