Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatting decimals using string format

public static string PadZero(this double number, int decimalPlaces)
    {
        var requiredFormat = "0." + "".PadRight(decimalPlaces, '0');
        var something = $"{number:requiredFormat}";

        return number.IsNotZero() ? something: string.Empty;
    }

This is a helper function to pad zeros to a double number, user can pass the number of zeros that is required to be padded through decimalPlaces. Above function fails my unit tests, output received is {requiredFormat} in all test cases. I have just replaced: var something = $"{number:0.00}"; with a generic variable requiredFormat that can handle any number of zero padding.

like image 464
smons Avatar asked Apr 30 '26 08:04

smons


1 Answers

There are two problems with your example. The first is that the value of something is not going to produce a string that can be used to format a number. The second is that you are not using something to perform a number format by using string.format.

So first off, the statement:

var something = $"{number:requiredFormat}";

is not going to give you the result that you want, which would be a string that looks something like:

{0:0.0000}

Try changing the code to read:

var something = $"{{0:{requiredFormat}}}";

If you do Console.WriteLine(something) after that statement executes you can inspect the value of something to make sure it is what you are looking for.

After that, change this line:

return number.IsNotZero() ? something: string.Empty;

to read:

return number.IsNotZero() ? string.Format(something, number) : string.Empty;

Even with Interpolated Strings, you have to build the variable format and apply it in two separate steps.

Hope that helps.

like image 127
rsbarro Avatar answered May 01 '26 21:05

rsbarro