How to format float for display

I have a float numer e.g. 3.638524 but can be any float. Is there any support to format it so that it always has exactly 3 decimal places: 3.639 in example above?

(Rounding is not important, can be 3.638 also)

Took this from someone on the forum :

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

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’ll need to call

ToTruncatedString(MyNumber, 3)

Not optimized though so use with caution :slight_smile:

1 Like

Thanks a lot!

Yes, I came with a similare approach in the end, but I was kinda expecting the engine to have better support for formatting.

Something like ToString(float, int), where int would be the number of decimals…

Yep, I agree, guess it will come one day !