英文:
Float to string without scientific notation?
问题
在Erlang/Elixir中,有没有一种好的方法将浮点数转换为字符串,不使用科学计数法,也不指定想要的小数位数?
这两种方法都不符合我的需求。
`:erlang.float_to_binary(decimals: 10)`: 会产生尾随的零小数位数
`float_to_binary(100000000000.0, [short]).`: 会打印科学计数法
英文:
Is there a good way to convert floats to strings in Erlang/Elixir, without scientific notation, and without specifying how many decimal digits I want?
Neither of these do what I need.
:erlang.float_to_binary(decimals: 10)
: gives trailing zero decimals
float_to_binary(100000000000.0, [short]).
: prints scientific notation
答案1
得分: 6
您可以提供compact
选项来修整尾随的零:
iex> :erlang.float_to_binary(100000000000.0, [:compact, decimals: 20])
"100000000000.0"
请注意,浮点数无法准确表示为十进制数,因此可能会导致意外的结果。例如:
iex> :erlang.float_to_binary(0.1 + 0.2, [:compact, decimals: 10])
"0.3"
iex> :erlang.float_to_binary(0.1 + 0.2, [:compact, decimals: 20])
"0.30000000000000004441"
英文:
<!-- language-all: lang-elixir -->
You can provide the compact
option to trim trailing zeros:
iex> :erlang.float_to_binary(100000000000.0, [:compact, decimals: 20])
"100000000000.0"
Note however that floats cannot be accurately represented as decimals, so you may end up with unexpected results. For example:
iex> :erlang.float_to_binary(0.1 + 0.2, [:compact, decimals: 10])
"0.3"
iex> :erlang.float_to_binary(0.1 + 0.2, [:compact, decimals: 20])
"0.30000000000000004441"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论