开发者

problem with Double.ToString Method

开发者 https://www.devze.com 2023-03-03 02:17 出处:网络
I am using this: dSize.ToString(\"#.#\", System.Globalization.CultureInfo.CurrentCulture); Where dSize is a double. it works fine when dSize is somethin开发者_运维问答g like 2.5 BUT if dSize is so

I am using this:

dSize.ToString("#.#", System.Globalization.CultureInfo.CurrentCulture); 

Where dSize is a double. it works fine when dSize is somethin开发者_运维问答g like 2.5 BUT if dSize is something like 3 - so it does not have decimal part - it is returning "3" which is wrong. I want it to return "3.0" so still with one decimal point.

Any thoughts?


Use a 0 to indicate that the digit should be printed even if it is zero:

dSize.ToString("#.0", System.Globalization.CultureInfo.CurrentCulture)

This will print .3 instead of 0.3; if you want the digit before the decimal point to be printed too, use a 0 there as well:

dSize.ToString("0.0", System.Globalization.CultureInfo.CurrentCulture)


Use

dSize.ToString("#.0", CultureInfo.CurrentCulture);

# is a digit placeholder and will be printed if there is a digit in the number in that position.

0 is a digit placeholder that will print the digit if there is one, or zero if there is no number in that position.

Reference: Custom Numeric Format Strings


Take a look at Custom Numeric Format Strings as well as Custom Number Format Strings Output Examples on MSDN.

Those should prove useful in conjunction with the answer that @Timwi provided.

0

精彩评论

暂无评论...
验证码 换一张
取 消