Fixed # of decimal places after the point

Blitz3D Forums/Blitz3D Beginners Area/Fixed # of decimal places after the point

Sir_LANs-a-lot(Posted 2005) [#1]
Hi,

Probably a really simple answer but I'm a bit stuck on it:

I want to create a floating point number to 2 decimal places, but creating a value thus:

myvar# = 0.0

prints out to varying decimal places from 0-4:

25.0
12.3333

etc..

I even tried converting it to a string value and truncating the string like so:

stat$=Str$(saccuracy#)+"00"
stat$=Left$(stat$,Len(stat$)-2)

But it still wont print correctly.. =/

Any help appreciated.

Cheers


Rhyolite(Posted 2005) [#2]
Well, off the top of my head so dont grumble if its not right ;)

First add 0.005 to the var to round it to the nearest. Then convert to a string. Next find the decimal point (".") using the appriopiate command (there is one, but cant remember it) then see how many characters come after the decimal point. Then either truncate the string or pad out with zero's.

Hope that helps a bit,
Rhy :)


Koriolis(Posted 2005) [#3]
Function f2s$(f#, decimals%)
	Local i = Floor(f)
	f = f - i
	Local e = (10^decimals)
	Local i2 = e*10+Int(f*e)
	Return i+"."+Right(i2, decimals)
End Function

Print f2s(12.0503, 1)
You're welcome, I'm really bored today :)


Rhyolite(Posted 2005) [#4]
Of course Koriolis, thats a better way and probably quicker during runtime.

Rhy :)


Sir_LANs-a-lot(Posted 2005) [#5]
Thanks Koriolis :)

Looks to be rather more complicated than I first thought it was going to be!


markcw(Posted 2005) [#6]
an easier way would be to use an integer
to represent the 2 floating points,
eg. 1234 would represent 12.34


Koriolis(Posted 2005) [#7]
In what is it easier? If all he needs is to print the value with a fixed number of decimals, why going to the troubles of constantly converting from this integer representation to the float value, whenever he needs to access it?


tonyg(Posted 2005) [#8]
Can you use...
variable#=25.111234
Print Int(variable*100)*.01

for 2 decimal places and adjust the values for others (i.e. *1000 * 0.001


Koriolis(Posted 2005) [#9]
If you read carefully you'll see he wants 25 to print as 25.00, not 25.0. From what I understand anyway.


markcw(Posted 2005) [#10]
well, he is printing to check he gets 2
decimal points but didn't say he needs
to print 2 decimal points.

i just suggested another way to maintain
a 2-decimal-point structure, but i think
your way is better, in most cases anyway,
maybe all. :)


Sir_LANs-a-lot(Posted 2005) [#11]
I'm just a bit surprised that Blitz doesn't have such a function in it! - Something like:

fdp# = fval(myvar#,2)

or something..

;)

Anyhoo, thanks for the replies guys.