Reputation: 199
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.
I tried {0:£#,0} to try and get an idea of what was happening and again 23699.99 was rounded to 23700.
Can anybody explain why this happens please?
Thankyou in advance.
Upvotes: 2
Views: 7907
Reputation: 3275
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
Upvotes: 0
Reputation: 16904
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.
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.
If you want to round down use Math.Floor.
Upvotes: 6