Formating floating point/double for display

BlitzMax Forums/BlitzMax Programming/Formating floating point/double for display

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

! your 50 result is WEIRD. This code on my PC:

Local test#=50
Print test
Print ccRoundFloatToString(test,1)
Print ccRoundFloatToString(test,2)
Print ccRoundFloatToString(test,3)

Function ccRoundFloatToString$(number:Float,decimals:Int)
	'This gets rid of any floating point inaccuracies such as 1.4 stored in a float
	'displaying as 1.39999 etc.
	Local t:Int = 10^decimals
	Local result% = Floor(number * t + 0.5)
	'Convert result into a string	
	Local display$ = String(result)
	'do we need to append a leading zero for numbers less than 1?
	'Now put in a decimal point at the correct place.
	While Len(display)-decimals <= 0
		display = "0"+display
	Wend
	If decimals > 0 Then display = Mid(display,1,Len(display)-decimals)+"."+Mid(display,Len(display)-decimals+1,decimals)
	Return display
End Function


gives:


50.0000000
50.0
50.00
50.000



Thanks for testing btw.

Dreamora: oops, just noticed you added in leading zeros which I did with a while loop. Your for loop should be faster as Len only needs to be evaluated once by the for loop. Changing mine now.