将浮点数转换为字符串而不使用科学计数法?

huangapple go评论63阅读模式
英文:

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&gt; :erlang.float_to_binary(100000000000.0, [:compact, decimals: 20])
&quot;100000000000.0&quot;

Note however that floats cannot be accurately represented as decimals, so you may end up with unexpected results. For example:

iex&gt; :erlang.float_to_binary(0.1 + 0.2, [:compact, decimals: 10])
&quot;0.3&quot;
iex&gt; :erlang.float_to_binary(0.1 + 0.2, [:compact, decimals: 20])
&quot;0.30000000000000004441&quot;

huangapple
  • 本文由 发表于 2023年7月12日 23:04:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定