Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Float to string with fixed precision #541

Open
svenroy opened this issue Mar 16, 2024 · 4 comments
Open

Float to string with fixed precision #541

svenroy opened this issue Mar 16, 2024 · 4 comments

Comments

@svenroy
Copy link

svenroy commented Mar 16, 2024

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

@lpil
Copy link
Member

lpil commented Mar 16, 2024

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

@lpil lpil changed the title Consider introducing a Decimal module for rounding functionality Float to string with fixed precision Mar 16, 2024
@lpil lpil transferred this issue from gleam-lang/gleam Mar 16, 2024
@Davidjustice28
Copy link

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

@markholmes
Copy link
Member

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

@leo-210
Copy link

leo-210 commented Aug 7, 2024

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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants