[bb] FloatString by skidracer [ 1+ years ago ]

Started by BlitzBot, June 29, 2017, 00:28:40

Previous topic - Next topic

BlitzBot

Title : FloatString
Author : skidracer
Posted : 1+ years ago

Description : float to string conversion with n decimal points

Code :
Code (blitzbasic) Select
Function FloatString$(f#,dp=2)
a$=Int(f*(10^dp))
l=Len(a$)
If l<=dp a$=Right$("000000",dp+1-l)+a$
Return Left$(a$,Len(a$)-dp)+"."+Right$(a$,dp)
End Function



Comments :


barryem(Posted 1+ years ago)

 This might be a little simpler and a little faster depending on the internals of the compilerCall it with either:print using$(number, decimals)ortext x,y, using$(number, decimals); n# is the number to convert; dec is the number of decimal places wantedFunction using$(n#, dec)   s$ = Str$ n#   t$ = Left$(s$, Len(s$) - Instr(s$, ".")+ dec -1)   Return t$End FunctionDoes anyone know the internals of Blitz3D enough to know if this sort of thing is faster or slower than calling a function in a DLL, assuming the function in the DLL is itself fairly effecient?Or, maybe more to the point, is Blitz3D fast enough with little stuff like this that we don't have to care most of the time?Barry


AntonyWells(Posted 1+ years ago)

 Strings are slow in b3d, so almost defintely faster to to pass it on to a .dll.Your above example, you need to enclose function pars that return a value within brackets, otherwise they'll return 0,"". ()


DJWoodgate(Posted 1+ years ago)

 Barry, I think he has not done it like that because Blitz does not show the full floating point accuracy when it converts to a string, and it also may use exponential format, i.e. 5.121218 will convert to "5.12122" and 0.00001 will convert to "1.e-005", which you may not want. (Well in fact exponential format might be useful for storing floats in strings or text files (XML perhaps) if it was accurate but it is subject to the same rounding effects). Blitz float to string conversion does not deal with large numbers, which are still well within the 23 bit range of the mantissa, very well either. Try Print Float(1048577) for instance.  More pointless rounding.Skidracers routine needs fixing to deal with larger numbers and small negatives though, like -0.00001 for instance.Here is a similar effort from me intended to display a number in a fixed field size with leading spaces centred on the decimal point, which (cough) was not working too well either.  Hopefully fixed now though.  Max number is still limited to what will be stored in an Int, but it calculates the fractional part separately. <a href="codearcse031.html?code=34" >Format$ (number,digits [,places])</a><div class="quote"> Or, maybe more to the point, is Blitz3D fast enough with little stuff like this that we don't have to care most of the time?  </div>Indeed.