How to trim a float to 2 significant places
Blitz3D Forums/Blitz3D Programming/How to trim a float to 2 significant places
| ||
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. |
| ||
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 |
| ||
Stevie, thanks for the feedback - that is one sweet little function and I'm implementing it now. |
| ||
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. |
| ||
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: ![]() |
| ||
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 |
| ||
if you need a function that returns a formated stringFunction FToS$(f#,NbDecimal%=1) Local n = 10^NbDecimal Local i% = f*n : Print i : Return (i/n)+"."+Right(i,NbDecimal) End Function |
| ||
_PJ_ & Bobysait - thanks also for your implementations of truncating the unrequired decimal places, its appreciated, BP. |
| ||
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" |