Currently if we use ToString()
to convert a float in to a string, the trailing 0’s remain like so: 10.000000
.
Hi Axel,
you could convert to int and print that. Would that work for you?
if (IntValue := Int[FloatValue]):
Print("{IntValue}")
The conversion should be performed in a failure context.
Not in my case as I sometimes want to display 7.50
or 7.5
instead of 7.500000
, for example.
The extra 0’s are not needed, especially now we have API to display floats through various devices and I haven’t found a way to parse a string to remove those 0’s
I see; in your case, would you like to remove all trailing zeroes, or truncate to X decimal places?
In an ideal world we’d be able to select the # of decimal places but if not, removing trailing 0s is fine.
I’ve created a couple of functions that should give you the results you need.
<#
Returns the index of the first occurrence of SearchChar in Str.
Fails if SearchChar isn't found.
The function must be <transacts> for now to mutate local data (FoundIndex).
#>
FindCharIndex(SearchChar:char, Str:[]char)<transacts><decides>:int=
var FoundIndex:int = 0
var Found:logic = false
for (X -> Char : Str, not Found?):
if (Char = SearchChar):
set FoundIndex = X
FoundIndex
<#
Returns the smaller of two int values
Verse only provides Min(:float, :float) for now.
#>
Min(X:int, Y:int)<computes>:int=
if (X < Y) then X else Y
# Returns Number converted to a string, truncated to Decimals places.
ToTruncatedString(Number:float, Decimals:int):[]char=
var Str:[]char = ToString(Number)
if:
DotIndex := FindCharIndex['.', Str]
StopIndex := if (Decimals > 0) then Min(DotIndex+Decimals+1,Str.Length) else DotIndex
set Str = Str.Slice[0, StopIndex]
Str
You’d use ToTruncatedString(MyFloat, MyDecimalPlaces)
as your string to print.
Please keep in mind that this isn’t the most performant way to do this, the string traversal in FindCharIndex
is not optimal due to a workaround that’s needed for now.
Also in the future, we’ll most likely provide a different approach that doesn’t require parsing the string character by character.
Hopefully, this works for you. Feel free to ask any questions about the code
Perfect. Thanks @DiG3!