Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Format A Number to Precision in Elixir?

Tags:

elixir

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
like image 897
Emily Avatar asked Apr 21 '17 07:04

Emily


People also ask

How do you change the precision of a number?

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

How do you round a float in Elixir?

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

How do you round double to 1 decimal place in Swift?

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.


Video Answer


2 Answers

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"
like image 98
MartinElvar Avatar answered Oct 14 '22 02:10

MartinElvar


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

like image 32
Dan Draper Avatar answered Oct 14 '22 02:10

Dan Draper