简体   繁体   中英

How can I force a number to have 3 digits while keeping ALL decimal places?

In c#, I want to force 0s when converting from double to string in case a number is lower than 100, the only challenge is that I want to keep all decimal places. Examples

58.3434454545 = 058.3434454545

8.343 = 008.343

I tried with ToString + a format provider but I'm not certain what's the correct provider for keeping all decimal places

You can use formatter strings for .ToString() , documented here .

To do what you want you can use this as example, noting the maximum digits for double is 17:

double numberA = 58.3434454545;
numberA.ToString("000.##############"); //058.3434454545

double numberB = 8.343;
numberB.ToString("000.##############"); //008.343

This is a rather ass ugly solution but if you wanted the number of decimals to be dynamic you could try something like this:

private string FormatDouble(double dbl)
{
    int count = BitConverter.GetBytes(decimal.GetBits((decimal)dbl)[3])[2];
    var fmt = string.Concat("000.", new string('#', count));
    return dbl.ToString(fmt);
}

Call it like this:

Console.WriteLine(FormatDouble(58.3434454545123123));
Console.WriteLine(FormatDouble(8.3431312323));

And your output would be this:

058.3434454545123

008.3431312323

I'm sure there is a much better way to do this and I'm not sure about performance, but hey it works and you don't have to guess the number of decimals you need, so that's a plus

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM