How to convert 1234.5678 into 1234.56 in C#?
I am trying to use
double abc = 1234.5678;
Console.WriteLine(abc.ToString("N2"));
Console.ReadKey(开发者_开发技巧);
but that is yielding
1.234,57
instead of
1234.56
How can I accomplish this?
Specify the invariant culture for formatting:
Console.WriteLine(abc.ToString("N2", CultureInfo.InvariantCulture));
It's still going to round it up to 1,234.57 though. It's printing the comma now because you've explicitly said you want the "N" format which includes thousands separators.
If you use "F2" it will give "1234.57":
Console.WriteLine(abc.ToString("F2", CultureInfo.InvariantCulture));
I'm not sure the best way to stop it from rounding up...
try this
double abc = 1234.5678;
Console.WriteLine("{0}", Math.Floor(abc*100)/100 );
Console.ReadKey();
// 1234.56
or make your own Floor()
function
public double Floor(double value, int digits)
{
double n = Math.Pow(10, digits);
return Math.Floor(value * n) / n;
}
You can use Math.Round
like this:
double abc = 1234.5678;
double rounded = Math.Round(abc, 2);
Console.WriteLine(rounded);
And it will output only two fractional digits.
精彩评论