rhai icon indicating copy to clipboard operation
rhai copied to clipboard

Decimal values are serialized as floats

Open matthiasbeyer opened this issue 3 months ago • 1 comments

https://github.com/rhaiscript/rhai/blob/b157ab0d56e95cd870a6b59c16516425ee51b501/src/serde/serialize.rs#L36-L55

This converts a Decimal to a float, which is an issue for roundtripping serialized to deserialized and back.

The issue where this appeared for me is:

I have an ID which gets correctly parsed from a blob of data (with deserializing a map of Dynamic) to a Decimal, which is enabled as a feature. But when sending a serialized blob again, where that Decimal is a part of, the Serialize implementation of Dynamic causes it to be serialized as f64.

You mentioned in https://github.com/rhaiscript/rhai/issues/587#issuecomment-1732509827 that one can consider such numbers as i64 as well, but that does not work with serialization and deserialization, if one of that converts to float.

Do you know of a way how I can make it to serialize as a integer number? Is there currently a way with rhai that I am missing?

matthiasbeyer avatar Oct 14 '25 13:10 matthiasbeyer

Well, serde only supports a fixed number of primitive types to serialize to.

If you don't want floats, the only alternative is to serialize Decimal to a string.

It is not really possible to serialize it into an i64 because the Decimal type is larger than that... I believe it is 128 bits. At the very least you need to serialize it as two i64 numbers.

If you want roundtripping, string is the correct format, but Rhai does not provide this off the shelf as the default is to serialize into a float. You'd need to write your own serialization and deserislization function.

schungx avatar Oct 14 '25 13:10 schungx