C # loss accuracy when splitting double

The function “1004233” is passed below the function and displays the following result:
D1 = 1.004233
D2 = 0.00423299999999993
D3 = 4232.99999999993
D4 = 4232

I need D4 to print 4233, not 4232. How do I stop this loss of accuracy?

public string someFunc(String s){
        string retval = "0";
        try{
            int id = int.Parse(s);
            double d = (double)id / (double)1000000;
            Console.WriteLine("D1 = " + d);
            d = d - Math.Truncate(d);
            Console.WriteLine("D2 = " + d);
            d = d * (double)1000000;
            Console.WriteLine("D3 = " + d);
            retval = "" + Math.Truncate(d);
            Console.WriteLine("D4 = " + retval);
        }catch(Exception ex){}
        return retval;
}
+3
source share
2 answers

This is a standard floating point question .

Use instead decimal.
Although they decimalalso do not have infinite accuracy, they are implemented in base 10, so they will give you the expected results.

+12
source

Source: https://habr.com/ru/post/1750720/