ericmj / decimal

Arbitrary precision decimal arithmetic

Home Page:https://hexdocs.pm/decimal/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to format a number to a certain precision?

GildedHonour opened this issue · comments

Instead of 1.1 I want to print it as 1.10

Instead of 3 I want to print it as 3.00

How to do that?

It is not currently possible but I am open to contributions. A new function that works like Decimal.reduce/1 but can set a specific precision that you then pass to Decimal.to_string(decimal, :normal) would work.

What's the workaround for now? Convert decimal to string, then parse it to Float and then print it with the amount of zeros I want?

iex(6)> Decimal.new(33.553333) |> Decimal.round(2) |> Decimal.to_string()
"33.55"

iex(7)> Decimal.new(33) |> Decimal.round(2) |> Decimal.to_string()       
"33.00"

This will work, won't it?

You are right, I forgot that Decimal.round also increases precision.