floating point print function

BlitzMax Forums/BlitzMax Programming/floating point print function

rdodson41(Posted 2006) [#1]
Im trying to create a function to print a floating point number with just as many decimal places as needed (ie. no trailing zeros at the end). This isn't specifically bmx related but in general i was wondering if there is an algorithm to do this.


Scott Shaver(Posted 2006) [#2]
Something like this:

velocityDelta = (Double(SliderValue(vdStepper))/Double(200))-1
Local s:String = ""+velocityDelta
' truncate the string to include only 7 characters
s = s[..7]
print "Velocity Delta: "+s


only look for the decimal place and truncate based on it.


Dreamora(Posted 2006) [#3]
The simpler version is a print with

left(string(float_number),instr(".",string(float_number)) + dec)

where dec is the amount of decimal places you want.

Cutting of all zeros is a little problem because in reality the computer will "never" have only zeros there ... (number representation can't be precise enough with float, not even double can ...)


Scott Shaver(Posted 2006) [#4]

Print DecToString(5.635412512523)
Print DecToString(5.635412512523,2)
Print DecToString(5.635412512523,3)

Function DecToString:String(value:Double,places:Int=5)
	Return Left(String(value),Instr(String(value),".") + places)
End Function


5.63541
5.63
5.635


rdodson41(Posted 2006) [#5]
Yeah, I knew I could just hack off some decimal places like that, but you are losing some numbers in there. I want to get all the digits that are in the number, but the problem is if you just do something like Print 2.5 you get 2.50000000 or something. So i want Print 2.5 to be 2.5 and I think I've found a way but I still have to finalize it.


Dreamora(Posted 2006) [#6]
The problem is 2.4 for example does not exist as float and thus it can't work by definition of IEEE floating point ...


rdodson41(Posted 2006) [#7]
What do you mean 2.4 isn't a float?


VP(Posted 2006) [#8]
He means that the real number 2.4 cannot be expressed exactly as the value 2.4 when using the standard math (IEEE) routines available in blitz (and most other languages). 2.4 can only be approximated.


Tom Darby(Posted 2006) [#9]
Sushimasta,

Probably not optimal, but fast enough:

1. Convert the float to a string.
2. Loop through the string character by character, starting at the "end" and working backwards:
2a. If the current character = "0" then continue;
2b. Else, this is your "trim point"; lop off everything after the current character and print what remains.


rdodson41(Posted 2006) [#10]
Yeah tom I was thinking of doing something like that, but I didnt think of starting from the end so that might be what i need, thanks all