开发者

double To String

I need a double to string to be displayed with max X chars after the decimal separator.

I tried

?string.Format("{0,10}", 1.234567890123456789)
"1,2345678开发者_StackOverflow9012346"

?string.Format("{0:F10}", 1,234567890123456789)
"1,0000000000"


Given that this is homework, I'll point you to the relevant documentation instead of giving you the code:

  • Standard Numeric Format Strings
  • Custom Numeric Format Strings
  • Composite Format Strings

Note that if you're happy with exactly X decimal places, it's relatively easy with a standard numeric format string. If you want at most X decimal places (but fewer if possible), you may need to use a custom numeric format string. At least as far as I've seen...


Here's a bigger hint:

Console.WriteLine(String.Format("{0:F1}", Math.Pi)); // Prints 3.1
Console.WriteLine(String.Format("{0:F2}", Math.Pi)); // Prints 3.14
Console.WriteLine(String.Format("{0:F3}", Math.Pi)); // Prints 3.141


You should probably use the String.Format function to format your numbers. To show a number with 2 decimals use:

String.Format("{0.00}",MyNumber);


Jons got the right direction, I use the collection http://www.csharp-examples.net/string-format-double/ over at csharp-examples as I dont deal with these everyday but atleast once a week (just enough to forget), these snippets should get you what you need.


I'll add to what the others suggested (String.Format("{0:0.0000000000}", number)) for example, if you need to always have 10 decimals after the decimal separator, that the String.Format formats the numbers based on the current culture, so in the USA it'll use the . as decimal separator, in Europe the ,. If you need to format a number in a "fixed" "default" culture you can do this: String.Format(CultureInfo.InvariantCulture, "{0:0.0000000000}", number). If you need to format in a specific culture: String.Format(new CultureInfo("it-IT"), "{0:0.0000000000}" (this will use Italian Culture).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜