How to trim a float to 2 significant places

Blitz3D Forums/Blitz3D Programming/How to trim a float to 2 significant places

Blitzplotter(Posted 2013) [#1]
Is there a Blitz function to do this, or do I have to convert the float to a string and curtail it that way - thanks.


Stevie G(Posted 2013) [#2]
There are probably better ways to do this. The function below trims to sf's rather than rounding to sf's.

ROUND( 3.12345, 3 ) = 3.123

Function ROUND#( q#, Dp = 3 )

	Local Val#, Ints, Dec

	Dp = 10^Dp
	Val = Floor( q * Dp )
	Val = Val / Dp

	Return Val

End Function



Blitzplotter(Posted 2013) [#3]
Stevie, thanks for the feedback - that is one sweet little function and I'm implementing it now.


Yasha(Posted 2013) [#4]
What do you want this for? If it's for display, modifying a string probably is actually the best way to do it as you can guarantee perfect results (and anyway, in that situation, it's also literally the thing you want to do). Otherwise you might run into difficulties caused by the fact that floating point doesn't work well with the concept of decimal places and might give you odd - and untidy - results on some inputs (I'm guessing, it might not).

If it's for math, I would recommend you consider the options of either keeping full-precision all the way through whatever you're doing, or switching to integers, as rounding in the middle of math operations can cause major headaches later on.


Blitzplotter(Posted 2013) [#5]
Its for displaying a dynamic 'average' speed in Km/H & MPH during training run playback, 1 decimal place is sufficient - the maximum I can seem to maintain for any distance is around the 6.0MPH (Can go up to 9.5 at a push, but that is only for a brief period).

Thanks for the fb Yasha & Stevie:




_PJ_(Posted 2013) [#6]
This should work as intended.
Note that although the function can be modified easily to return a Float value, this will always have the decimal places truncated to minimum if there aren't enough significant figures.

;Function Round#(f_Val#, n_Places=2); Float Version - Easier for arthmetic
Function Round$(f_Val#, n_Places=2); String Version - Better for Display
	Local s_Word$=Str(f_Val)
	Local n_Dp=Instr(s_Word,".")
	s_Word=Str(f_Val)+String("0",n_Places+1)
	s_Word=Left(s_Word,n_Dp+n_Places)
	;Return Float#(s_Word); For Float Version
        Return s_Word$; For String Version
End Function



Bobysait(Posted 2013) [#7]
if you need a function that returns a formated string

Function FToS$(f#,NbDecimal%=1)
	Local n = 10^NbDecimal
	Local i% = f*n : Print i : Return (i/n)+"."+Right(i,NbDecimal)
End Function



Blitzplotter(Posted 2013) [#8]
_PJ_ & Bobysait - thanks also for your implementations of truncating the unrequired decimal places, its appreciated, BP.


_PJ_(Posted 2013) [#9]
Incidentally, I should have realised - standard form exponentials may screw with the string formatting:

0.020576 = 2.0576E-2
Would result in:
"0.02" ... "2.05"