1

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?

Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
user5313398
  • 713
  • 3
  • 9
  • 28

3 Answers3

3

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.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • @user5313398 which ever you feel most comfortable using. Which one will make most sense to you in 6 months time when you've forgotten this problem and revisit the code? Pick that one. – ChrisF May 30 '16 at 17:35
  • I will pick this one String.Format("{0:0.00}", value) but what is the format with 0:0.00? – user5313398 May 30 '16 at 17:37
2

You can try to use .ToString() method with custom format, like this:

value.ToString("#.##");
Serhiy Chupryk
  • 438
  • 2
  • 5
  • 15
1

Just use the code

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

Badruzzaman
  • 41
  • 1
  • 7