简体   繁体   中英

Verify and print double value in 2 decimal places

I am reading a string value and try to confirm its value its currency value via this method

double value;
if (!double.TryParse(sumValue, out value) || Math.Round(value, 2) != value)
{
    MessageBox.Show("Not a double value");
}

This works fine. The issue when I use this MessageBox.Show(Math.Round(value, 2)) it does not show the value in 2 decimal places. What changes can I do for that and also am I using the right method to verify?

How the value is output will depend on the actual value.

While Math.Round(value, 2) will round the value to two decimal places, if that rounded value is 1.00 or 1.50 (for example) it will be displayed as "1" or "1.5" as the trailing zeros are omitted by default.

If you want to display the value to 2 decimal places then there are a number of ways to do this. All require you to call either string.Format or explicitly call .ToString with a format parameter.

One is to use:

MessageBox.Show(String.Format("{0:0.00}", value));

The first "0" represents the number itself and the the "0.00" indicates to the formatting engine that this is a floating point number with two decimal places. You can use "#:##" instead.

Source

Another is:

MessageBox.Show(value.ToString("F"));

Which is the fixed point format specifier. Adding a number specifies the number of decimal places (2 is the default). Source

Given that you say of your code that "This works fine." then your verification step is correct. You are checking that the value is a number and that the value rounded to 2 decimal places is the value you want. There's nothing more you need to do.

您可以尝试使用具有自定义格式的.ToString()方法,如下所示:

value.ToString("#.##");

Just use the code

MessageBox.Show(Convert.ToString(Math.Round(value, 2)));

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