C# Converting 20 digit precision double to string and back again

Use the “R” numeric format string: double d = 0.00034101243963859839; string s = d.ToString(“R”); //… double d2 = double.Parse(s); if(d == d2) { //– Success } The R stands for “round-trip”. From the linked document: This format is supported only for the Single and Double types. The round-trip specifier guarantees that a numeric value converted … Read more

Why is this simple calculation of two doubles inaccurate? [duplicate]

Floating point numbers (in this case doubles) cannot represent decimal values exactly. I would recommend reading David Goldberg’s What every computer scientist should know about floating-point arithmetic This applies to all languages that deal with floating point numbers whether it be C#, Java, JavaScript, … This is essential reading for any developer working with floating … Read more

BigDecimal from Double incorrect value?

When you create a double, the value 0.3 cannot be represented exactly. You can create a BigDecimal from a string without the intermediate double, as in new BigDecimal(“0.3”) A floating point number is represented as a binary fraction and an exponent. Therefore there are some number that cannot be represented exactly. There is an analogous … Read more

Formatting a string into columns using String Interpolation

You can use Alignment Component for this purpose. Like this: Console.WriteLine($”value: {d,-17} {s}”); The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the … Read more

Unexpected result in long/int division

When you are using a binary operator, both arguments should be of a same type and the result will be in their type too. When you want to divide (int)/(long) it turns into (long)/(long) and the result is (long). you shouldmake it (double)/(long) or (int)/(double) to get a double result. Since double is greater that … Read more