serhio
serhio

Reputation: 28586

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,23456789012346"

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

Upvotes: 0

Views: 303

Answers (5)

Pat
Pat

Reputation: 16921

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

Upvotes: 1

xanatos
xanatos

Reputation: 111940

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).

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503954

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

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...

Upvotes: 3

Jake Kalstad
Jake Kalstad

Reputation: 2065

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.

Upvotes: 0

Kibbee
Kibbee

Reputation: 66162

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);

Upvotes: 0

Related Questions