Formatting Numbers with Significant Figures in C#

Formatting numbers with significant figures in C#

See: RoundToSignificantFigures by "P Daddy".

I've combined his method with another one I liked.

Rounding to significant figures is a lot easier in TSQL where the rounding method is based on rounding position, not number of decimal places - which is the case with .Net math.round. You could round a number in TSQL to negative places, which would round at whole numbers - so the scaling isn't needed.

Also see this other thread. Pyrolistical's method is good.

The trailing zeros part of the problem seems like more of a string operation to me, so I included a ToString() extension method which will pad zeros if necessary.

using System;
using System.Globalization;

public static class Precision
{
// 2^-24
public const float FLOAT_EPSILON = 0.0000000596046448f;

// 2^-53
public const double DOUBLE_EPSILON = 0.00000000000000011102230246251565d;

public static bool AlmostEquals(this double a, double b, double epsilon = DOUBLE_EPSILON)
{
// ReSharper disable CompareOfFloatsByEqualityOperator
if (a == b)
{
return true;
}
// ReSharper restore CompareOfFloatsByEqualityOperator

return (System.Math.Abs(a - b) < epsilon);
}

public static bool AlmostEquals(this float a, float b, float epsilon = FLOAT_EPSILON)
{
// ReSharper disable CompareOfFloatsByEqualityOperator
if (a == b)
{
return true;
}
// ReSharper restore CompareOfFloatsByEqualityOperator

return (System.Math.Abs(a - b) < epsilon);
}
}

public static class SignificantDigits
{
public static double Round(this double value, int significantDigits)
{
int unneededRoundingPosition;
return RoundSignificantDigits(value, significantDigits, out unneededRoundingPosition);
}

public static string ToString(this double value, int significantDigits)
{
// this method will round and then append zeros if needed.
// i.e. if you round .002 to two significant figures, the resulting number should be .0020.

var currentInfo = CultureInfo.CurrentCulture.NumberFormat;

if (double.IsNaN(value))
{
return currentInfo.NaNSymbol;
}

if (double.IsPositiveInfinity(value))
{
return currentInfo.PositiveInfinitySymbol;
}

if (double.IsNegativeInfinity(value))
{
return currentInfo.NegativeInfinitySymbol;
}

int roundingPosition;
var roundedValue = RoundSignificantDigits(value, significantDigits, out roundingPosition);

// when rounding causes a cascading round affecting digits of greater significance,
// need to re-round to get a correct rounding position afterwards
// this fixes a bug where rounding 9.96 to 2 figures yeilds 10.0 instead of 10
RoundSignificantDigits(roundedValue, significantDigits, out roundingPosition);

if (Math.Abs(roundingPosition) > 9)
{
// use exponential notation format
// ReSharper disable FormatStringProblem
return string.Format(currentInfo, "{0:E" + (significantDigits - 1) + "}", roundedValue);
// ReSharper restore FormatStringProblem
}

// string.format is only needed with decimal numbers (whole numbers won't need to be padded with zeros to the right.)
// ReSharper disable FormatStringProblem
return roundingPosition > 0 ? string.Format(currentInfo, "{0:F" + roundingPosition + "}", roundedValue) : roundedValue.ToString(currentInfo);
// ReSharper restore FormatStringProblem
}

private static double RoundSignificantDigits(double value, int significantDigits, out int roundingPosition)
{
// this method will return a rounded double value at a number of signifigant figures.
// the sigFigures parameter must be between 0 and 15, exclusive.

roundingPosition = 0;

if (value.AlmostEquals(0d))
{
roundingPosition = significantDigits - 1;
return 0d;
}

if (double.IsNaN(value))
{
return double.NaN;
}

if (double.IsPositiveInfinity(value))
{
return double.PositiveInfinity;
}

if (double.IsNegativeInfinity(value))
{
return double.NegativeInfinity;
}

if (significantDigits < 1 || significantDigits > 15)
{
throw new ArgumentOutOfRangeException("significantDigits", value, "The significantDigits argument must be between 1 and 15.");
}

// The resulting rounding position will be negative for rounding at whole numbers, and positive for decimal places.
roundingPosition = significantDigits - 1 - (int)(Math.Floor(Math.Log10(Math.Abs(value))));

// try to use a rounding position directly, if no scale is needed.
// this is because the scale mutliplication after the rounding can introduce error, although
// this only happens when you're dealing with really tiny numbers, i.e 9.9e-14.
if (roundingPosition > 0 && roundingPosition < 16)
{
return Math.Round(value, roundingPosition, MidpointRounding.AwayFromZero);
}

// Shouldn't get here unless we need to scale it.
// Set the scaling value, for rounding whole numbers or decimals past 15 places
var scale = Math.Pow(10, Math.Ceiling(Math.Log10(Math.Abs(value))));

return Math.Round(value / scale, significantDigits, MidpointRounding.AwayFromZero) * scale;
}
}

Round a double to x significant figures

The framework doesn't have a built-in function to round (or truncate, as in your example) to a number of significant digits. One way you can do this, though, is to scale your number so that your first significant digit is right after the decimal point, round (or truncate), then scale back. The following code should do the trick:

static double RoundToSignificantDigits(this double d, int digits){
if(d == 0)
return 0;

double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1);
return scale * Math.Round(d / scale, digits);
}

If, as in your example, you really want to truncate, then you want:

static double TruncateToSignificantDigits(this double d, int digits){
if(d == 0)
return 0;

double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1 - digits);
return scale * Math.Truncate(d / scale);
}

String Format % with significant figures

You can control the number of digits before and after the decimal point (separator). Controlling the total number of digits (before and after) is going to require some programming.

The format {0:0.00%} ought to work, giving outputs like 0.12, 1.23 and 12.34

How to format a double with fixed number of significant digits, regardless of the decimal places?

Use G3 format specificator:

  String result1 = 123.4567.ToString("G3");
String result2 = 1.234567.ToString("G3");

Or via String.Format:

  String result = String.Format("{0:G3}", 12.3456789);

Printing Significant Digits

See the custom format strings here :http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
I think I understand your question... does

   current.ToString("#0.#");

give you the behavior you are asking for? I often use "#,##0.####" for similar labels.
Also, see this question: Formatting numbers with significant figures in C#

C# number format: display n significant number of digits?

Although there are formats that would let you drop some or all of the fraction, no format would let you drop some of the significant digits of the whole part of the number.

If you would like to keep the first three digits of the whole number, you need to divide the value so that its whole part has only three digits.

One approach to computing the divisor is taking log10N, checking if it is above 2, and dividing by 10 to the corresponding power:

private static void Print(double x) {
int n = (int)Math.Log10(x);
if (n > 2) {
x /= Math.Pow(10, n-2);
}
Console.WriteLine((int)x);
}

Demo.

Can NumberFormatInfo use significant digits?

I started with just using .ToString(), but I want to make sure my decimal separator, grouping separator, and so on are all used properly, so I ended up implementing it this way, and I'm pretty happy with the results.

value is the double I'm trying to format.

CultureInfo culture = this.CurrentCulture;
string decimalSeparator = culture.NumberFormat.NumberDecimalSeparator;
string temp = value.ToString();
string[] splitter = temp.Split(decimalSeparator[0]);
int numDigitsToDisplay = 0;
if( splitter.Length > 1)
{
numDigitsToDisplay = splitter[1].Length;
}
numDigitsToDisplay = Math.Min(10, numDigitsToDisplay); // Make sure no more than 10 digits are displayed after the decimal point
NumberFormatInfo tempNFI = (NumberFormatInfo)culture.NumberFormat.Clone();
tempNFI.NumberDecimalDigits = numDigitsToDisplay;
double roundedValue = Math.Round((double)value, numDigitsToDisplay, MidpointRounding.AwayFromZero); // just in case the number's after-decimal digits exceed the maximum I ever want to display (10)
return roundedValue.ToString("N", tempNFI);

C# Format double limiting significant digits but restrict scientific notation

I couldn't figure out a way to do it, as it's a bit unconventional, but this extension may work:

public static string DoubleLimited(this double n){      
return n < 100 ? $"{n:G2}" : n.ToString("#0.");
}

used like

var num = 1234.0;
Console.WriteLine(num.DoubleLimited());


Related Topics



Leave a reply



Submit