简体   繁体   中英

Storing a double with 2 digit precision

How do I convert a double to have precision of 2 places?

For ex:

    double x = 1.00d;           
    Console.WriteLine(Math.Round(x,2,MidpointRounding.AwayFromZero));
//Should output 1.00 for me, but it outputs just 1.

What I'm looking for is to store 1.00 in a double variable which when printed to console prints 1.00.

Thanks, -Mike

"x" stores the number - it doesn't pay attention to the precision.

To output the number as a string with a specific amount of precision, use a format specifier , ie:

Console.WriteLine(x.ToString("F2"));

double is an IEEE-754 double-precision floating point number. It always has exactly 53 bits of precision. It does not have a precision that can be exactly represented in "decimal places" -- as the phrase implies, "decimal places" only measures precision relative to the base-10 number system.

If what you want is simply to change the precision the value is displayed with, then you can use one of the ToString() overloads to do that, as other answers here point out.

Remember too that double is an approximation of a continuous real value; that is, a value where there is no implied discrete quantization (although the values are in fact quantized to 53 bits). If what you are trying to represent is a discrete value, where there is an implicit quantization (for example, if you are working with currency values, where there is a significant difference between 0.1 and 0.099999999999999) then you should probably be using a data type that is based on integer semantics -- either a fixed-point representation using a scaled integer or something like the .NET decimal type.

This is not a question of storing , it is a question of formatting .

This code produces 1.00 :

double x = 1.00d;
Console.WriteLine("{0:0.00}", Math.Round(x, 2, MidpointRounding.AwayFromZero));

The decimal data type has a concept of variable precision. The double data type does not. Its precision is always 53 bits.

The default string representation of a double rounds it slightly to minimize odd-looking values like 0.999999999999 , and then drops any trailing zeros. As other answers note, you can change that behavior by using one of the type's ToString overloads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM