Fr33dan
Fr33dan

Reputation: 4337

Use scientific notation only if needed

I want to parse a double value into a string. I want my number to have a specified number of digits (that I won't know until runtime). If this number can be expressed with a non-zero value in number of digits this is what I want. If the number comes out as zero's like this I want it expressed in scientific notation.

Some examples will make this more clear, this assumes I wanted 3 digits:

Value: .2367 Output: "0.23"

Value: .00367 Output: "3.67E-3"

Value: 22.3 Output: "22.3"

Value: 3364.0 Output: "3.36E3"

My work around solution would use the ToString() method and the N numeric format string and if it results in zero's revert to the E format string, but this feels like reinventing the wheel. Does anyone know if a built in method to do this?

Upvotes: 5

Views: 12215

Answers (1)

Paul Sasik
Paul Sasik

Reputation: 81517

Have you looked at using the General Number Format Specifier?

The general ("G") format specifier converts a number to the most compact of either fixed-point or scientific notation, depending on the type of the number and whether a precision specifier is present.

Some samples from the documentation:

double number;

number = .0023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 0.0023

number = 1234;
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));
// Displays 1.2E+03

number = Math.PI;
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));
// Displays 3.1416 

Upvotes: 15

Related Questions