Float to n decimals

Monkey Forums/Monkey Beginners/Float to n decimals

yiotoo(Posted 2014) [#1]
I am trying to transform a random number to a float with 1 decimal.

so i call the function this way
Gravidade = Round(Rnd(1, 20), 1)


and the function is (found it on http://www.monkey-x.com/Community/posts.php?topic=753)
Function Round:Float(N:Float, DecimalPlaces:Int)
	Return Float(Int(N * Pow(10.0,DecimalPlaces))) / Pow(10.0,DecimalPlaces)
End Function


but it is not working, so i replaced the function for this (same but with steps)

Function Round:Float(N:Float, DecimalPlaces:Int)
		Local i:Int
		Local j:Float
		Local jj:Float
		Print "N= " + N
		i = Int(N * Pow(10.0, DecimalPlaces))
		Print "i= " + i
		j = Float(i)
		Print "j= " + j
		jj = j / Pow(10.0, DecimalPlaces)
		Print "jj= " + jj
		
		Return jj
	
	
End Function


And i am obtening this results:

N= 1.492829442024231
i= 14
j= 14.0
jj= 1.3999999761581421

N= 11.15460205078125
i= 111
j= 111.0
jj= 11.100000381469727

N= 2.9717435836791992
i= 29
j= 29.0
jj= 2.9000000953674316

the number seems too close , but i can't figured out
How can i get a float with like 15,4 or 15,34?


ziggy(Posted 2014) [#2]
You can't control the number of decimals on any float. That's how they're computed and stored. See this:

http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

So, if you want a fixed number of digits of precision, I would recommend you to use Integer variables to store your data multiplied per 10, and just add a dot before last digit when showing this data to screen. Divide all operations that may require it by 10.0 for internal calculations. I'm afraid that's the most reliable way (paired with proper rounding).


yiotoo(Posted 2014) [#3]
that is sad, but Ty :)


yiotoo(Posted 2014) [#4]
Is there a way to transform the number int into an array of string, to put the dot?
I am having difficult to put the dot, the number could bel big or small, and has different distance between the numbers .


skid(Posted 2014) [#5]
Here is the method I use

Function FloatToString$(f#)
	Local sign$
	If f<0
		f=-f
		sign="-"
	Endif
	Local i=f*10
	Local s$=i
	Local l=s.Length-1
	If l=0
		Return sign+"0."+s
	Endif
	Return sign+s[..l]+"."+s[l..]	
End Function

Function Main()
	Print FloatToString(0)
	Print FloatToString(0.1)
	Print FloatToString(-0.1)
	Print FloatToString(10.1)
	Print FloatToString(22)
End



yiotoo(Posted 2014) [#6]
thanks very much!!


skid(Posted 2014) [#7]
and slightly modified:

Function FloatToString$(f#,dp)
	Local sign$
	If f<0
		f=-f
		sign="-"
	Endif	
	Local pow=Pow(10,dp)
	Local i=f*pow
	Local s$=i
	Local l=s.Length-dp
	If l=0
		Return sign+"0."+s
	Endif
	If l<0
		Return sign+"0."+"00000"[..-l]+s
	Endif	
	Return sign+s[..l]+"."+s[l..]	
End Function

Function Main()
	Local f#=1.0/10
	Print ""+f
	Print FloatToString(f,1)
	Print FloatToString(0.0,1)
	Print FloatToString(-f,1)
	Print FloatToString(10+f,1)
	Print FloatToString(22,1)
End