change decimal print

BlitzMax Forums/BlitzMax Beginners Area/change decimal print

flying willy(Posted 2004) [#1]
Hi, is using left$ the best way to show less decimal places with floats?

numbers are a bit long looking in my editor at the moment, wondering if using left$ is the way to go...


dan_upright(Posted 2004) [#2]
i knocked this up in two minutes while running a bath, so there may be ninja optimisations i'm not seeing, but it works ok

f:Float = 1.0 / 3.0
Print "f = " + f
For i = 1 To 9
	Print "decimals$(f, " + i + ") = " + decimals$(f, i)
next

End

Function decimals$(f:Float, places:Int)

	Local a$ = String(f)
	Local p = Instr(a$, ".")
	Local b$ = Left$(a$, p)
	b$ :+ Mid$(a$, p + 1, places)

	Return b$

End function



flying willy(Posted 2004) [#3]
Cheers dan!


fredborg(Posted 2004) [#4]
This takes care of Scientific Notation as well...ie. 5e+021 :
strict

Local a:Float = 0.00092304
Print a+" -> "+FloatToFixedPoint(a)
Local b:Float = 120592345792834.0235234
Print b+" -> "+FloatToFixedPoint(b)
Local c:Float = 1.0/3.0
Print c+" -> "+FloatToFixedPoint(c)

Function FloatToFixedPoint:String(f:Float,decimals:Int=3)

	Local i:Long = (10^decimals)*f
	Local value:String = String.fromlong(i)
		
	If value.length<=decimals
		Return "0."+(RSet("",decimals-value.length)).Replace(" ","0")+value
	Else
		Return value[0..value.length-decimals] + "." + value[value.length-decimals..value.length]  
	EndIf
	
End Function 
Slices and string methods ROCK!


flying willy(Posted 2004) [#5]
Where's the blitzmax code archive! ? :)

And thanks!


Hotcakes(Posted 2004) [#6]
Isn't it... in the code archives section? ;]