我有这个十进制数 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 takeContext
into consideration. It uses it only when you use someDecimal
opearation.
关于decimal - 在 Elixir 中舍入十进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41907100/