user2732622
user2732622

Reputation: 11

Output Format for double

I've simple question on formatting. I've a double returning a number that will always be a multiple of 0.5. (e.i. the number can be 125.5, 125, 160, 171.5) In my output window I am currently printing something like this:

double number;
(number).ToString("###0.0");

However, in the case my number is an integer, such as 125, this returns a value of 125.0, which I would like the number to be printed out as 125, whilst keeping the capability of printing out the decimal number in case the double number was for example 126.5.

Does anybody know how I can do this? Thanks!

Upvotes: 1

Views: 94

Answers (2)

Nerdroid
Nerdroid

Reputation: 13996

In C# Use String.Format

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"

String.Format("{0:0.##}", 123.4567);                    // "123.46"
String.Format("{0:0.##}", 123.4);                       // "123.4"
String.Format("{0:0.##}", 123.0);                       // "123"

String.Format("{0:00.0}", 123.4567);                    // "123.5"
String.Format("{0:00.0}", 23.4567);                     // "23.5"
String.Format("{0:00.0}", 3.4567);                      // "03.5"
String.Format("{0:00.0}", -3.4567);                     // "-03.5"

String.Format("{0:0,0.0}", 12345.67);                   // "12,345.7"
String.Format("{0:0,0}", 12345.67);                     // "12,346"

String.Format("{0:0.0}", 0.0);                          // "0.0"
String.Format("{0:0.#}", 0.0);                          // "0"
String.Format("{0:#.0}", 0.0);                          // ".0"
String.Format("{0:#.#}", 0.0);                          // ""

String.Format("{0:0.00;minus 0.00;zero}", 123.4567);    // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567);   // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0);         // "zero"

Upvotes: 2

David M
David M

Reputation: 72930

Try using this format string:

"###0.#"

I'm assuming from your capitalisation of ToString that this relates to C#.

Upvotes: 1

Related Questions