stdlib icon indicating copy to clipboard operation
stdlib copied to clipboard

Float to string with fixed precision

Open svenroy opened this issue 1 year ago • 5 comments
trafficstars

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

svenroy avatar Mar 16 '24 15:03 svenroy

Hello! Good idea, thank you. It would go in the float module and we'd need to determine a name.

lpil avatar Mar 16 '24 16:03 lpil

@lpil I am currently working on this. How do we feel about to_fixed_string or to_string_fixed for the function name?

Davidjustice28 avatar Mar 23 '24 20:03 Davidjustice28

Since round, truncate, and to_string already exist, I think to_fixed_string sounds like a good name. Anyone else have ideas?

markholmes avatar Mar 24 '24 01:03 markholmes

In Godot Engine, there is a different way of doing this I like : snapped(x: Float, step: Float)

"Returns the multiple of step that is the closest to x" 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".

leo-210 avatar Aug 07 '24 15:08 leo-210