Elixir-将float转换为字符串 [英] Elixir - Convert float to string

查看:83
本文介绍了Elixir-将float转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何将浮点数转换为字符串/二进制,但看起来并不像看起来那么简单

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"

我们需要 1200.00出来...只是不使用指数符号

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

推荐答案

如果没有关于用例的更多详细信息,这将为您提供所需的结果:

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

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

它使用的是erlang float_to_binary / 2 ,将在elixir 1.4中弃用( https://github.com/elixir-lang/elixir/blob/v1.3.2/lib/elixir/lib/float.ex#L225 ):

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

在Elixir 1.8中,仍然有 Float .to_string / 1 。已弃用 Float.to_string / 2 ,建议直接使用:erlang.float_to_binary / 2

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.

这篇关于Elixir-将float转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆