decimal - 在 Elixir 中舍入十进制数

标签 decimal elixir

我有这个十进制数 Elixir:

c1 = Decimal.div(a1, b1)
# => #Decimal<0.006453859622556080696687234694>

如何将其四舍五入为小数点后位数较少的较短数字?

最佳答案

正如@Dogbert 在评论中所说 - 最简单的方法就是 round一个号码:

iex> alias Decimal, as: D
nil
iex> d = D.div(D.new(1), D.new(3))
#Decimal<0.3333333333333333333333333333>
iex> D.round(d, 5)
#Decimal<0.33333>

编辑:

以下不完全正确!!精度是小数系数中的位数,而不是数字的实际四舍五入。因此,如果将 Precision 设置为 5,然后对数字进行一些计算,则只会得到系数中总位数等于 5 的数字。例如:
iex> D.set_context(%D.Context{D.get_context | precision: 5})
:ok
iex> a = D.div(D.new(100.12345), D.new(3))
#Decimal<33.374>

对于完全错误的信息,我真的很抱歉!!

But if you expect every operation to be rounded then you can set Context first and after setting it, Decimal will use the newly set precision on every operation.

iex> D.set_context(%D.Context{D.get_context | precision: 5})
:ok
iex> a = D.div(D.new(1), D.new(3))
#Decimal<0.33333>
iex> b = D.new("0.006453859622556080696687234694")
#Decimal<0.006453859622556080696687234694>
iex> D.add(a,b)
#Decimal<0.33978>

Please note that parsing a number with Decimal.new/1 doesn't take Context into consideration. It uses it only when you use some Decimal opearation.

关于decimal - 在 Elixir 中舍入十进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41907100/

相关文章:

c# - 将请求 QueryString 转换为十进制

ubuntu - (File.Error) 无法读取文件 "": no such file or directory

elixir - Ecto - 验证相关模型的存在

java - 如何更改速度模板中的小数分隔符?

elixir - 如何将键值对放入具有可变键名的映射中

logging - Logger 无与伦比的返回

elixir - 通过委托(delegate)现有功能实现协议(protocol)

c# - 如何精确反序列化十进制属性

vb.net - VB.NET 中数字的小数位

.net - LINQ:如何为查询结果四舍五入小数值?