在Elixir中四舍五入小数 [英] Rounding a Decimal number in Elixir

查看:94
本文介绍了在Elixir中四舍五入小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个十进制数字药剂:

I have this Decimal number Elixir:

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

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

How can I round it to a shorter number with a smaller number of digits after the decimal point?

推荐答案

正如@Dogbert在评论中说的那样-进行回合的最简单方法数字:

As @Dogbert said in comment - the easiest way to just round a number:

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的数字。例如:

Below is not entirely true!! Precision is number of digits in coefficient of decimal, not the actual rounding of number. So if you set Precision to 5 and then you make some calculations on the numbers you will only get numbers with total number of digits in coefficient equal to 5. For instance:

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>

对于完全错误的信息,我感到非常抱歉!

I'm really sorry for totally wrong info!!


但是,如果您希望对每个操作都进行四舍五入,则可以先设置
Context ,然后再设置十进制将对每个操作使用新设置的
精度。

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>

请注意,使用 Decimal.new/1 没有考虑
Context 。仅当您使用某些
十进制运算时,它才会使用它。

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.

这篇关于在Elixir中四舍五入小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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