Elixir - Convert float to string

谁都会走 提交于 2019-12-10 02:38:09

问题


I am trying to figure out how to convert a float to a string/binary but seems like its not as easy as it looks

iex(1)> to_string(1200.00)
"1.2e3"

iex(2)> Float.to_string(1200.00)
"1.2e3"

We need "1200.00" to come out...just not in the exponent notation


回答1:


Without further details about your usecase, this will give you your desired result:

iex(1)> Float.to_string(1200.00, decimals: 2)
"1200.00"

It is using erlang's float_to_binary/2 and will be deprecated in elixir 1.4 (https://github.com/elixir-lang/elixir/blob/v1.3.2/lib/elixir/lib/float.ex#L225):

def to_string(float, options) do
    :erlang.float_to_binary(float, expand_compact(options))
end

In elixir 1.8, there still is Float.to_string/1. Float.to_string/2 is deprecated and the suggestion is to use :erlang.float_to_binary/2 directly.



来源:https://stackoverflow.com/questions/38734113/elixir-convert-float-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!