質問

On this page it says:

The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.

Is "00" a special case or an example? Why is is specifically singled out?

What is the rounding mode of formats other than "00"? It specifically mentions integer rounding; what about rounding after n decimal places?

What does ToString("0") do? Is it the same as "00" but no rounding?

I tried ToString("00") and it gave me a zero padded number, where I was expecting just a single digit.

役に立ちましたか?

解決

"00" is not a special case, just an example, although the way it is worded makes it sound like a special case.

From the documentation:

The "0" custom format specifier serves as a zero-placeholder symbol. If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string. The position of the leftmost zero before the decimal point and the rightmost zero after the decimal point determines the range of digits that are always present in the result string.

So ToString("00") means you will have a minimum of two digits to the left of the decimal point, and NO digits to the right of the decimal point (those get rounded). Likewise, ToString("000") will give you a minimum of 3 digits, and so on.

You can also control the exact number of digits that will appear to the right of the decimal point. ToString("000.00") will give you at least 3 digits to the left of the decimal point, and exactly 2 digits to the right. Any extra digits to the right of the decimal point will be rounded.

Here are some passing assertions to demonstrate:

var value = 67.89;
Assert.AreEqual("68", value.ToString("0"));
Assert.AreEqual("68", value.ToString("00"));
Assert.AreEqual("068", value.ToString("000"));
Assert.AreEqual("067.9", value.ToString("000.0"));
Assert.AreEqual("067.89", value.ToString("000.00"));
Assert.AreEqual("067.890", value.ToString("000.000"));

他のヒント

It looks like a documentation bug to me, their examples show it as a padded integer output.

int.ToString("format") 

Is the equivalent to

string.Format("0:format", int)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top