'ToString format for fixed length of output - mixture of decimal and integer

I'm writing some code to display a number for a report. The number can range from 1. something to thousands, so the amount of precision I need to display depends on the value.

I would like to be able to pass something in .ToString() which will give me at least 3 digits - a mixture of the integer part and the decimal part.

Ex:

1.2345 -> "1.23"
21.552 -> "21.5"
19232.12 -> "19232"

Using 000 as a format doesn't work, since it doesn't show any decimals, neither does 0.000 - which shows too many decimals when the whole part is larger than 10.



Solution 1:[1]

I don't think this can be done with ToString() alone.

Instead, start by formatting the number with 2 trailing digits, then truncate as necessary:

static string FormatNumber3Digits(double n)
{
    // format number with two trailing decimals
    var numberString = n.ToString("0.00");

    if(numberString.Length > 5)
        // if resulting string is longer than 5 chars it means we have 3 or more digits occur before the decimal separator
        numberString = numberString.Remove(numberString.Length - 3);
    else if(numberString.Length == 5)
        // if it's exactly 5 we just need to cut off the last digit to get NN.N
        numberString = numberString.Remove(numberString.Length - 1);

    return numberString;
}

Solution 2:[2]

Here's a regex, that will give you three digits of any number (if there's no decimal point, then all digits are matched):

@"^(?:\d\.\d{1,2}|\d{2}\.\d|[^.]+)"

Explanation:

^ match from start of string

either

\d\.\d{1,2} a digit followed by a dot followed by 1 or 2 digits

or

\d{2}\.\d 2 digits followed by a dot and 1 digit

or

[^.]+ any number of digits not up to a dot.

First divide your number and then call ToString() before the regex.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mathias R. Jessen
Solution 2 Poul Bak