如何在Elixir中格式化数字?

Emi*_*ily 10 elixir

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
Run Code Online (Sandbox Code Playgroud)

Mar*_*var 24

只想提供一个替代Dogbert的优秀答案.

也可以使用:erlang.float_to_binary/2

恩.

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"
Run Code Online (Sandbox Code Playgroud)


Dan*_*per 9

小数位数已弃用,现在在Elixir中已删除,因此对于以后找到此帖子的人们而言,从Elixir v1.6开始,以下是操作方法:

123.176
|> Float.round(2)
|> Float.to_string

# => "123.78"
Run Code Online (Sandbox Code Playgroud)

  • 例如,当您有 123.10 时,此解决方案不起作用,它返回“123.1” (4认同)
  • 请小心:*这是 2019 年的正确答案。其他答案(有更多选票)实际上不起作用:/ (3认同)

Dog*_*ert 5

据我所知,Elixir的标准库中没有类似的东西,但是您可以使用:io_lib.format/2Erlang在点后打印带有特定位数的浮点数:

iex(1)> :io_lib.format("~.3f", [123.101])
['123.101']
iex(2)> :io_lib.format("~.6f", [123.101])
['123.101000']
iex(3)> :io_lib.format("~.3f", [123.0])
['123.000']
iex(4)> :io_lib.format("~.6f", [123.0])
['123.000000']
Run Code Online (Sandbox Code Playgroud)

返回的值是iolist,可以根据IO.iodata_to_binary/1需要使用转换为二进制(许多采用二进制的函数也可以iolist直接接受,例如IO.puts/1):

iex(5)> :io_lib.format("~.6f", [123.0]) |> IO.iodata_to_binary
"123.000000"
Run Code Online (Sandbox Code Playgroud)

~.0f不起作用,但是为此您可以简单地调用trunc/1

iex(6)> trunc(123.123)
123
Run Code Online (Sandbox Code Playgroud)


小智 5

这些答案大多是奇怪的.首先,她没有说过转换成字符串.其次,肯定没有必要跳进二郎之地!

为了:

Starting number: 123.101

Ending number: 123.101000 # Adding 3 digits to the precision of a float.

iex> 123.101 |> Decimal.new() |> Decimal.round(6)
#Decimal<123.101000>


Starting number: 123

Ending number: 123.000 # Adding 3 digits to the precision of an integer.

iex> 123 |> Decimal.new() |> Decimal.round(3)    
#Decimal<123.000>


Starting number: 123.101

Ending number: 123.1 # removing precision

iex> 123.101 |> Decimal.new() |> Decimal.round(1)
#Decimal<123.1>


Starting number: 123.000

Ending number: 123 # removing precision

iex> 123.000 |> Decimal.new() |> Decimal.round(0)
#Decimal<123>
Run Code Online (Sandbox Code Playgroud)

一旦你有一个数字Decimal,你可以做你想要的,例如转换为浮点数,转换为字符串等.

iex> 123.101 |> Decimal.new() |> Decimal.round(6) |> Decimal.to_string()
"123.101000"

iex> 123.101 |> Decimal.new() |> Decimal.round(6) |> Decimal.to_float() 
123.101

iex> 123.101 |> Decimal.new() |> Decimal.round(0) |> Decimal.to_integer()
123
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我建议只在工作Decimal,直到你完成所有的数据操作,例如使用Decimal.mult(num1, num2),Decimal.div(num1, num2)Decimal石头!