Ivan Kochurkin
Ivan Kochurkin

Reputation: 4501

0.0.ToString(".####") returns empty string

Why 0.0.ToString(".####") returns empty string but not 0? What format string should I use for proper output?

Upvotes: 0

Views: 4135

Answers (2)

D Stanley
D Stanley

Reputation: 152596

Think about what you're asking - you ask for no required digits before the decimal point and up to 4 optional significant digits after the decimal point.

Since 0.0 has no significant digits before or after the decimal, it returns nothing.

To give you the proper format string we need the expected output in each of the following cases:

  • A number >= 1
  • A number between 0 and 1 (exclusive)
  • 0

Note that you can use section separators to explicitly say how you want to format positive numbers, negative numbers, and 0:

0.0.ToString(".####;-.####;0")   // returns "0"

The nice thing about using section separators (versus explicitly checking for 0) is that it will use the "0" format specifier if the formatted string would be equivalent to 0.

For example,

(-0.0000001).ToString(".####;-.####;0")

will return "0" since the small negative number will be rounded to four decimals based on your format specification.

Upvotes: 5

Alan
Alan

Reputation: 7951

To always show the digit for the 1s position, then you need to specify a zero in the string format specifier for that digit. See the following:

// outputs "0"
0.0.ToString("0.####")

If you want to show extra decimal places, even if they are zero, then you can also use zeros to do that:

// outputs "5.1000"
(5.1).ToString("0.0000")

For more information see: Custom Numeric Format Strings

If you want to show only the 1s position for the number zero.. then do this:

String text = (number == 0) ? "0" : number.ToString(".####");

Upvotes: 6

Related Questions