The Crystal Programming Language Forum

Fixed Point Deciamls

Is there a library or package like DecFP, to use fixed point decimals?

Not sure if this is what you’re looking for but Crystal has BigDecimal.

I’m not aware of any libraries doing this, but because Crystal is built on LLVM it wouldn’t be too hard to bind to the LLVM Fixed-Point Arithmetic Instrinsics. As an example of binding to LLVM functions, I did that with the LLVM Saturating Arithmetic Intrinsics in Saline.

No, the opposite, I want to do accounting to two decimal places, and not have arbitrary precision.

OK, I’ll have to look into doing that.

I think I have it fugured out, is there a difference, between fun and def?

You should read through the documentation on C Bindings.

Also note that the example I gave is complicated by macros, so you may not want to copy it exactly.

Also worth noting once you succeed in writing the bindings is that the LLVM functions I linked to use a base-2 scale factor. I don’t know if you’re already familiar with working that way from the other library you’ve mentioned, but I’m happy to explain further if you want.

I’m know how base-2 works, but I’m not famaliar with scale factors. Good to know that you’re dealing with C bindings, that is definatly an area that I need to look into further.

1 Like

I want to do accounting to two decimal places

@BrettKnoss , you could make cents you base unit, then multiply as applicable to get the dollars. Likewise for other currencies. If you’re just sticking to one currency, that should suffice.


But then wouldn’t the user still have to enter the price in cents?

Data representation is entirely different from how it’s displayed in the user interface. For example, you can easily parse/format a string as 123.45 $ while the internal representation equals 12345.


OK great, then that is probably the best way to go then.

BigDecimal plus round?

Julia has a DecFP package, but I used round every time anyways. I’m actually thinking Julia might be better for some things, and I can use concurance to direct, and then use Julia for parallel computing.