Haedrian
Haedrian

Reputation: 4328

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.

Upvotes: 0

Views: 953

Answers (4)

Simple way to implement this just write ToString("f2") for two decimal number just change this fnumber to get your required number of decimal values with integer values also.

Upvotes: 1

Poul Bak
Poul Bak

Reputation: 10929

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.

Upvotes: 1

41686d6564
41686d6564

Reputation: 19641

You could write an extension method for this:

public static string ToCustomString(this double d, int minDigits = 3)
{
    // Get the number of digits of the integer part of the number.
    int intDigits = (int)Math.Floor(Math.Log10(d) + 1);
    // Calculate the decimal places to be used.
    int decimalPlaces = Math.Max(0, minDigits - intDigits);
    
    return d.ToString($"0.{new string('0', decimalPlaces)}");
}

Usage:

Console.WriteLine(1.2345.ToCustomString());    // 1.23
Console.WriteLine(21.552.ToCustomString());    // 21.6
Console.WriteLine(19232.12.ToCustomString());  // 19232

Console.WriteLine(1.2345.ToCustomString(minDigits:4));    // 1.235

Try it online.

Upvotes: 3

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

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;
}

Upvotes: 2

Related Questions