Double 2 Decimal Places [duplicate]
Possible Duplicate:
How to round and format a decimal correctly?
I 开发者_运维知识库have this:
double xValue = 0.0;
double yValue = 0.0;
foreach (var line in someList)
{
xValue = Math.Round(Convert.ToDouble(xDisplacement - xOrigin), 2);
yValue= Math.Round(Convert.ToDouble(yDisplacement + yOrigin), 2);
sw.WriteLine("( {0}, {1} )", xValue, yValue);
}
When it does that math it is suppose to round to 2 decimal places.
HOWEVER,
..When a number is something like 6.397 it will round it to 6.4 and not include the trailing "0".
How can I add the "0" at the end of the number?
If I add this to BEFORE (unless there is a better way to do it?) the foreach loop above...:
string properX = xValue.ToString().Replace(".", "");
string properY = yValue.ToString().Replace(".", "");
How would I go about doing this?
Use a format string:
sw.WriteLine("( {0:0.00}, {1:0.00} )", xValue, yValue);
For documentation, look at Standard Numeric Format Strings. String.Format
and TextWriter.WriteLine
expose the same format options.
The first set of examples in this link:
http://www.csharp-examples.net/string-format-double/
// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"
Should be what you are looking for. It also details lots more.
MSDN documentation on string numeric formatting:
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SpecifierPt
This trailing zero has nothing to do with the number itself, but rather with its representation. So if you want to display it, there is nothing to change with the number - use string formats:
sw.WriteLine("( {0:0.00}, {1:0.00} )", xValue, yValue);
Use a numeric format string to display as many decimal places as you like:
sw.WriteLine("( {0:N2}, {1:N2} )", xValue, yValue);
Rather than round the value, which you may not want to do, you can do the rounding just as part of the output formatting:
WriteLine("{0:0.00}", value)
精彩评论