Use scientific notation only when necessary

I want to analyze the value doublein string. I want my number to have a certain number of digits (which I won’t know until done). If this number can be expressed with a non-zero value in the number of digits, this is what I want. If the number is zero, I want it to be expressed in scientific notation.

Some examples will make this more clear, this suggests that 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"

In my work around the solution, the ToString () method and the N number format will be used , and if this leads to a zero return to the format string E, but this is like reusing the wheel. Does anyone know if there is a built-in method for this?

+5
source share
1 answer

Have you considered using the Generic Number Format Conventions ?

A common format specifier ("G") converts a number to the largest number of compactness, either fixed or scientific notation, depending on the type of number and whether an accuracy specifier is present.

Some examples 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 
+14

All Articles