C# Double - Tostring() Formatting With Two Decimal Places But No Rounding

C# Double - ToString() formatting with two decimal places but no rounding

I use the following:

double x = Math.Truncate(myDoubleValue * 100) / 100;

For instance:

If the number is 50.947563 and you use the following, the following will happen:

- Math.Truncate(50.947563 * 100) / 100;
- Math.Truncate(5094.7563) / 100;
- 5094 / 100
- 50.94

And there's your answer truncated, now to format the string simply do the following:

string s = string.Format("{0:N2}%", x); // No fear of rounding and takes the default number format

Formatting a double to two decimal places

string.Format will not change the original value, but it will return a formatted string. For example:

Console.WriteLine("Earnings this week: {0:0.00}", answer);

Note: Console.WriteLine allows inline string formatting. The above is equivalent to:

Console.WriteLine("Earnings this week: " + string.Format("{0:0.00}", answer));

C# How to format a double to one decimal place without rounding

result=string.Format("{0:0.0}",Math.Truncate(value*10)/10);

Double ToString gives rounded result

See: MSDN for the standard ToString conversion:

If format is null or an empty string, the return value is formatted with the general numeric format specifier ("G").

This will show you, that the defaulted number format specifier "G", will default to max 15 digits if possible: G-format specifier

As requested:

double bigNum = 99999999999999.99;

Console.WriteLine(bigNum); //default
//100000000000000
Console.WriteLine(bigNum.ToString("G")); //explicit default
//100000000000000
Console.WriteLine(bigNum.ToString("G17")); //G17
//99999999999999.984

Format a double to two digits after the comma without rounding up or down

Have you tried

Math.Round(0.33333333333, 2);

Update*

If you don't want the decimal rounded another thing you can do is change the double to a string and then get get a substring to two decimal places and convert it back to a double.

doubleString = double.toString();
if(doubleString.IndexOf(',') > -1)
{
doubleString = doubleString.Substring(0,doubleString.IndexOf(',')+3);
}
double = Convert.ToDouble(doubleString);

You can use a if statement to check for .99 and change it to 1 for that case.



Related Topics



Leave a reply



Submit