What is the most direct, & efficient way to do this in Elixir?
Starting number: 123.101
Ending number: 123.101000 # Adding 3 digits to the precision of a float.
Starting number: 123
Ending number: 123.000 # Adding 3 digits to the precision of an integer.
Starting number: 123.101
Ending number: 123.1 # removing precision
Starting number: 123.000
Ending number: 123 # removing precision
To set the precision in a floating-point, simply provide the number of significant figures (say n) required to the setprecision() function as an argument. The function will format the original value to the same number of significant figures (n in this case).
ceil(number, precision \\ 0) Rounds a float to the smallest integer greater than or equal to num . ceil/2 also accepts a precision to round a floating-point value down to an arbitrary number of fractional digits (between 0 and 15).
Rounding Numbers in Swift By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.
Just want to supply a alternative to Dogbert's excellent answer.
It is also possible to use :erlang.float_to_binary/2
ex.
iex(5)> :erlang.float_to_binary(123.101, [decimals: 6])
"123.101000"
iex(6)> :erlang.float_to_binary(123.0, [decimals: 3])
"123.000"
iex(7)> :erlang.float_to_binary(123.101, [decimals: 1])
"123.1"
iex(8)> :erlang.float_to_binary(123.000, [decimals: 0])
"123"
Decimal has been deprecated and now removed in Elixir so for folks finding this post later, here is how to do it as of Elixir v1.6:
123.176
|> Float.round(2)
|> Float.to_string
# => "123.18"
edit: fixed typo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With