Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 701
Fr33dan Avatar asked Feb 25 '13 17:02

Fr33dan


People also ask

When Should scientific notation be used?

The primary reason for converting numbers into scientific notation is to make calculations with unusually large or small numbers less cumbersome. Because zeros are no longer used to set the decimal point, all of the digits in a number in scientific notation are significant, as shown by the following examples.

What are the rules for scientific notation?

Scientific Notation RulesThe exponent must be a non-zero integer, that means it can be either positive or negative. The absolute value of the coefficient is greater than or equal to 1 but it should be less than 10. Coefficients can be positive or negative numbers including whole and decimal numbers.

What are the 2 rules of scientific notation?

To write a number in scientific notation: - If you moved the decimal point to the left, make the exponent positive. - If you moved the decimal point to the right, make the exponent negative. Drop all trailing or leading zeroes.

Is scientific notation only used for large numbers?

Scientific notation is simply a way of writing numbers. It is especially useful in expressing very large or very small numbers because it is shorter and more efficient and it shows magnitude very easily.


1 Answers

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 
like image 167
Paul Sasik Avatar answered Sep 24 '22 19:09

Paul Sasik