Metadata icon indicating copy to clipboard operation
Metadata copied to clipboard

Type `System.Decimal` loses precision during serialization and deserialization when the value contains floating-point digits

Open lupuscaoticus opened this issue 1 year ago • 0 comments

Problem

When serializing and deserializing System.Decimal values, especially those with floating-point digits, there is a noticeable loss of precision. This can lead to incorrect values being processed in applications that rely on precise decimal calculations.

Reproduction

  1. Divide System.Decimal::MaxValue by 10.
  2. Serialize the Value using ConvertTo-Metadata.
  3. Deserialize the serialized value using ConvertFrom-Metadata.
  4. Compare the original and deserialized values.

Solution

  1. Append 'd' Suffix during serialization to the string representation of the System.Decimal value. This ensures that during deserialization, the value is correctly interpreted as a System.Decimal and not mistakenly as a System.Double.

Example

[String](                                      [Decimal]::MaxValue                            ) #* 79228162514264337593543950335
[String](                                      [Decimal]::MaxValue    | ConvertTo-Metadata    ) #* 79228162514264337593543950335
[String]( ConvertFrom-Metadata -InputObject  $([Decimal]::MaxValue    | ConvertTo-Metadata)   ) #* 79228162514264337593543950335
[String](                                      [Decimal]::MaxValue/10                         ) #* 7922816251426433759354395033.5
[String](                                      [Decimal]::MaxValue/10 | ConvertTo-Metadata    ) #* 7922816251426433759354395033.5
[String]( ConvertFrom-Metadata -InputObject  $([Decimal]::MaxValue/10 | ConvertTo-Metadata)   ) #! 7.92281625142643E+27 ($_ -Is [Double])
[String]( ConvertFrom-Metadata -InputObject "$([Decimal]::MaxValue/10 | ConvertTo-Metadata)d" ) #* 7922816251426433759354395033.5

lupuscaoticus avatar Nov 27 '24 11:11 lupuscaoticus