Code archives/Algorithms/FloatString

This code has been declared by its author to be Public Domain code.

Download source code

FloatString by skidracer2001
float to string conversion with n decimal points
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

barryem2004
This might be a little simpler and a little faster depending on the internals of the compiler

Call it with either:
print using$(number, decimals)
or
text x,y, using$(number, decimals)

; n# is the number to convert
; dec is the number of decimal places wanted
Function using$(n#, dec)
s$ = Str$ n#
t$ = Left$(s$, Len(s$) - Instr(s$, ".")+ dec -1)
Return t$
End Function

Does 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


AntonyWells2004
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,"". ()


DJWoodgate2004
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. Format$ (number,digits [,places])


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?


Indeed.


Code Archives Forum