简体   繁体   English

验证并打印小数点后两位的double值

[英]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. 当我使用此MessageBox.Show(Math.Round(value, 2))该问题未在2个小数位后显示该值。 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. 虽然Math.Round(value, 2)会将值四舍五入到小数点后两位,但如果舍入后的值是1.00或1.50(例如),则默认显示为尾随零,它将显示为“ 1”或“ 1.5” 。

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. 所有这些都要求您调用string.Format或使用format参数显式调用.ToString

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. 第一个“ 0”代表数字本身,而“ 0.00”则向格式化引擎指示这是一个带有两位小数的浮点数。 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). 加一个数字指定小数位数(默认为2)。 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))); MessageBox.Show(Convert.ToString(Math.Round(value,2)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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