How to round float to x decimal places?

@ChrisAI

This mostly comes down to a problem of converting between ints and floats in Verse. One thing you might have been missing is that you can multiply an int by 1.0 to turn it into a float. Here is a version of your original code with that + rounding integrated in.

QuickTest():logic =
    if:
        ((Round[10.12345 * 1000.0] * 1.0) / 1000.0) = 10.123
    then:
        return true
    else:
        return false

I also gave a quick go at writing a more generic version

RoundToDecimalPlaces(Value:float, DecimalPlaces:int)<varies><decides>:float =
    DecimalPlaces >= 0
    Multiplier := Pow(10.0, DecimalPlaces * 1.0)
    RoundedValues := Round[Value * Multiplier] * 1.0
    return RoundedValues / Multiplier

QuickTest():logic =
    if:
        RoundToDecimalPlaces[10.12345, 0] = 10.0
        RoundToDecimalPlaces[10.12345, 1] = 10.1
        RoundToDecimalPlaces[10.12345, 2] = 10.12
        RoundToDecimalPlaces[10.12345, 3] = 10.123
        RoundToDecimalPlaces[10.12345, 4] = 10.1234
        RoundToDecimalPlaces[10.12345, 5] = 10.12345
        RoundToDecimalPlaces[10.12345, 6] = 10.123450

        RoundToDecimalPlaces[10.56789, 0] = 11.0
        RoundToDecimalPlaces[10.56789, 1] = 10.6
        RoundToDecimalPlaces[10.56789, 2] = 10.57
        RoundToDecimalPlaces[10.56789, 3] = 10.568
        RoundToDecimalPlaces[10.56789, 4] = 10.5679
        RoundToDecimalPlaces[10.56789, 5] = 10.56789
        RoundToDecimalPlaces[10.56789, 6] = 10.56789
    then:
        return true
    else:
        return false
3 Likes