Search code examples
c#formattingdoublenumber-formatting

Stop Automatic Insignificant Decimal Truncating of Double


I have a double I want to store exactly as is without any of the following formatting:

Example 1: double a = 12. Gets formatted to: 12

Example 2: double b = 50.0 Gets formatted to: 50

Example 3: double c = 88.0000000000 Gets formatted to: 88

Is that possible (with some "magical" C# feature), or will I have to store it as a string like any other language? I saw Decimal has lots of options for formatting numbers but none of the ones I've tried so far get it quite the way I want it (only close).

I'm building a GUI calculator app for educational purposes and want to make sure I'm doing things in the best C# way (as I'm doing this project to familiarize myself with the language).

Thank you.

EDIT: Example: Double is set to 52.000 The user clicks a button in the application that appends the 52.000 with a 1. New number: 52.0001 Those decimals that were once insignificant now have meaning because if the zeros from 52.000 got taken away earlier then this number would be 52.1. Which is a completely different number from 52.0001. Hence why the zeros do matter in this situation.


Solution

  • You can't as double does not store insignificant digits.

    Your options:

    • use appropriate format if you just need to print zeros
    • switch to decimal that preserves the zeros (be careful constructing it so - Decimal data type is stripping trailing zero's when they are needed to display).
    • keep values as strings for display purposes and convert to numerical types when you want to do computations. Based on the edit this is the option you are looking for as you are building calculator - indeed text input should stay as text till user finally decides that input is complete.