stdlib
stdlib copied to clipboard
Float to string with fixed precision
In Javascript, I am able to do:
const value = 0.8999999999
const roundedValueAsString = value.toFixed(2)
console.log(roundedValueAsString) // "0.90"
console.log(typeof roundedValueAsString) // "string"
There is similar behaviour in Elixir
Hello! Good idea, thank you. It would go in the float module and we'd need to determine a name.
@lpil I am currently working on this. How do we feel about to_fixed_string or to_string_fixed for the function name?
Since round, truncate, and to_string already exist, I think to_fixed_string sounds like a good name. Anyone else have ideas?
In Godot Engine, there is a different way of doing this I like : snapped(x: Float, step: Float)
"Returns the multiple of
stepthat is the closest tox" Godot Engine docs
For example :
float.snapped(2.54, 0.1) // Returns 2.5
float.snapped(32.0, 2.5) // Returns 32.5
Then you use float.to_string on the rounded result.
This function could also be added to the int module.
The only problem I see would be that you can't add zeros at the end : the advantage of a to_fixed_string function would be that to_fixed_string(0.5, 2) returns "0.50".