Float to String

Monkey Targets Forums/Desktop/Float to String

Terrion(Posted 2015) [#1]
Hello. I have a problem with converting float into a string. I have a label(simply DrawText() thing), that shows value of a float variable. And if i change the value so i gets some numbers after the dot(like 2.7), it shows a lot of different numbers, i don't need. So, is there any way to round that value?

Also i tried to make a function for that.

Function FloatToString:String(f:Float)
	Local s:String
		
	s = String(f)
	If Int(s[s.Find(".") + 2 .. s.Find(".") + 3]) >= 5
		s = String(f + 0.1)
	Else
		s = String(f)
		
	EndIf
	
	s = s[ .. (s.Find(".") + 2)]
		
	Return s
End


But some values just drop out, like 1.9.
For example, if i take 1.9, it rounds to 2.0(with 1 number after dot accuracy), if i take 1.91 , it rounds to 1.9, when 1.91 is greater than 1.9.

Any ideas, please?


Gerry Quinn(Posted 2015) [#2]
One way is to convert to a large int, then insert a dot:

The following will give you the result to the nearest two decimal places (you will have to tweak it if you want the rounding to work properly on negative numbers too)

Local f:Float = 1.967
Local val:Int = Int( f * 100 + 0.5 )
Local str:String = String( val )
Local len:Int = str.Length()
Local output:String = str[ 0 .. len - 2 ] + "." + str[ len - 2 .. ]


Result: output = "1.97"

For one decimal place you would multiply by 10 and use len - 1 in the last line, etc.


ziggy(Posted 2015) [#3]
Gerry, your sample will fail for negative numbers. Tiny fix:
Local f:Float = -1.967
Local val:Int = Int(f * 100 + 0.5 * Sgn(f))
Local str:String = String( val )
Local len:Int = str.Length()
Local output:String = str[0 .. len - 2] + "." + str[len - 2 ..]



Terrion(Posted 2015) [#4]
Thanks a lot!


abakobo(Posted 2015) [#5]
you have to be aware that a lot of numbers doesn't exist in float and are slightly modified when stored in memory.

the most known example is that 0.1 does not exists in float! so it gives a very long number near 0.1!

see http://floating-point-gui.de/


Gerry Quinn(Posted 2015) [#6]
And that's the point of the rounding off. If x = 0.1, and 0.1 is 0.99999998 or 0.10000002, then Int( 0.1 * 1000 + 0.5 ) will still be 100 in either case.

|Thanks, ziggy, I knew there must be a simple fix for negative numbers, but I didn't have time to figure out something elegant so I just made it for positive only.


nullterm(Posted 2015) [#7]
I've always taken to using this for negatives...



abakobo(Posted 2015) [#8]
Sorry for my irrelevant answer... Bad reading of the question.


Terrion(Posted 2015) [#9]
ziggy, that function works right the way i needed, thank you again for that simple and elegant solution for that annoying problem.


EdzUp(Posted 2015) [#10]
Couldn't you use MyFloat.ToString() then locate the . In there :)