问题
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?
回答1:
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>
EDIT:
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!!
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.
回答2:
You can achieve it by:
rounded_c1 = Decimal.round(c1, 4)
in which the 4
means the number of digits you may want to leave after rounding.
You can also do ceiling or floor by :
ceil_c1 = Decimal.round(c1, 4, :ceiling)
floor_c1 = Decimal.round(c1, 4, :floor)
来源:https://stackoverflow.com/questions/41907100/rounding-a-decimal-number-in-elixir