Decimal.normalize w/o getting into "scientific" notation?

When “normalising” `Decimal` numbers it’s easy fall into something like this:

``````Decimal.normalize(Decimal.new("10.00"))
Decimal.new("1E+1")
``````

which is technically correct but rather unusable when all I want from this “normalisation” is getting rid of unneeded trailing zeroes (in this case the insignificant decimal part) while keeping the numbers “human readable”. `Decimal.round()` is not an option because sometimes the decimal part can be significant. I can imagine of course some ways of doing this “manually” but since I guess I am not the first one to have such not-so-exotic need, maybe there’s a ready solution out there?

What do you need the normalized human-readable form for? Eyeballing values as you code along seems to be the only valid scenario I can think of.

You can serialize the decimal back into a string, too.

I present those to the user(s). if the number has no significant decimal digits, I’d like not to show them. IOW - I want the user to see “10” if the `Decimal` is “10.00” but I want her to see “10.5” if the `Decimal` is “10.50” and so on.

I know - that’s what I do. And…

``````iex(1)> Decimal.to_string(Decimal.new("10.00"))
"10.00"
iex(2)> Decimal.to_string(Decimal.normalize(Decimal.new("10.00")))
"1E+1"
``````

You can do `Decimal.to_string(decimal, :normal)` to not get scientific formatting.

4 Likes

Gosh… :red face and facepalm: RTFM. Sorry. Of course that does the trick. I couldn’t believe there was nothing ready out there.