64 vs 32 bit double parsing issue with the round-trip format specifier "R"

Viewed 350

I've got a scenario in .net (4.6.1) where parsing a string representation of a 6dp floating point value produces different results in 32 and 64 bit mode.

[Fact]
public void ParseTest()
{
    var numText = "51.580133";
    double.Parse(numText)
        .ToString("R")
        .Should().Be(numText);
}

This test passes in 32 bit mode, but for 64 bit mode fails as the text generated is: "51.580132999999996"

I'd expect rounding issues like this with irrational numbers or numbers derived via an equation, but there is no ambiguity about the length and accuracy of the floating point here.

This is inside an older system so changing everything to decimal would take a significant effort.

Questions:

  1. Why does this happen?
  2. What options are there to reliably round / truncate this value to 6dp?

Update This works, and produces a different output to ToString("G6"):

[Fact]
public void ParseText()
{
    var numText = "51.580133";
    double.Parse(numText)
        .ToString("G8")
        .Should().Be(numText);
}
1 Answers
Related