简体   繁体   English

string.Format不带小数位会产生意外的舍入

[英]string.Format without decimal places gives unexpected rounding

I need to update some existing code so that a figure is (conditionally) displayed without any decimal places. 我需要更新一些现有代码,以便(有条件地)显示数字而没有任何小数位。

The following two lines are used dependent on whether a "£" sign is required. 根据是否需要“£”符号使用以下两行。

currency = string.Format(CultureInfo.CurrentCulture, "{0:£#,0.00}", data);

Or 要么

currency = string.Format(CultureInfo.CurrentCulture, "{0:#,0.00}", data);

I tried changing this code to use {0:£#,0} and whilst the decimal places are removed, a 'data' value of 23699.99 was rounded to 23700 rather than 23699. 我尝试更改此代码以使用{0:£#,0},并且删除了小数位后,“数据”值23699.99舍入为23700,而不是23699。

I tried {0:£#,0} to try and get an idea of what was happening and again 23699.99 was rounded to 23700. 我尝试{0:£#,0}尝试了解发生了什么,然后再次将23699.99舍入为23700。

Can anybody explain why this happens please? 有人可以解释为什么会这样吗?

Thankyou in advance. 先感谢您。

When you format a number it is always rounded to the nearest number with the precision you choose. 格式化数字时,它始终会以您选择的精度四舍五入到最接近的数字。 For example, if you format with one decimal place then 0.86 will round to 0.9 and 0.96 will round to 1.0. 例如,如果您将格式设置为小数点后一位,则0.86将四舍五入为0.9,而0.96将四舍五入为1.0。

Similarly, if you print with no decimal places 23699.99 will round to 23700 because 23700 is the number with no decimal places nearest to 23699.99. 同样,如果您不带小数位打印,则23699.99将四舍五入为23700,因为23700是没有小数位最接近23699.99的数字。

If you want to round down use Math.Floor. 如果要四舍五入,请使用Math.Floor。

Same as above but with example: 与上面相同,但带有示例:

using System;
using System.Globalization;

namespace testings
{
    class Program
    {
        static void Main(string[] args)
        {
            string currency;
            decimal data = 23699.99m;
            currency = string.Format(CultureInfo.CurrentCulture, "{0:£#,0}", data);
            Console.WriteLine(currency);

            currency = string.Format(CultureInfo.CurrentCulture, "{0:£#,0.00}", data);
            Console.WriteLine(currency);

            currency = string.Format(CultureInfo.CurrentCulture, "{0:£#,0.00}", Math.Floor(data));
            Console.WriteLine(currency);
            Console.ReadKey(false);
        }
    }
}

returns: 收益:

£23,700
£23,699.99
£23,699.00

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

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