I have just released a new decimal library for Nim that is based on the IEEE 754-2008 specification. https://github.com/JohnAD/decimal128
It has a pending PR for inclusion in the nimble directory.
Examples of use:
let a = newDecimal128("0.00009999999999999999999999999")
let b = newDecimal128("-Infinity")
let c = newDecimal128("1.23E+4023")
let d = newDecimal128("12.3E+4022")
assert c === d # for === to be true, both the numeric value and the number of significant digits must match
This is the spec used by both the BSON protocol and MongoDB database, which is why I wrote it. It successfully encodes and decodes NumberDecimal() fields. I'll be formally adding it to my bson and mongopool libraries this next week.
In general, however, it should also work for folks wanting decimal support and the associated tracking of significant digits.
For me, I pretty much have what I needed: import/export.
But I suspect folks will notice a big glaring problem: mathematical operators do not work yet.
You can't do a + b because a
proc `+`*(left, right: Decimal128): Decimal128
procedure has not been written yet.
So, the call-for-help:
If you are interested in having decimal library for Nim, please consider helping out by writing one of the operator procedures! An issue has been made for tracking progress: https://github.com/JohnAD/decimal128/issues/1
Thanks for considering this. I know folks have asked for a decimal library in Nim in the past. This could be a good opportunity to flush one out based on a known standard.
I wonder: nim could start supporting user defined litterals so you'd be able to write:
import fusion/decimal128
echo -0.123'dec128 + 12e-4022'dec128
nim parser would change to transform -0.123'dec128 into dec128("-0.123")
which feels more native (and would render as primitive type instead of as string)