decimal custom format string with fixed precision

2019-08-05 23:48发布

问题:

I've run into a situation which I think is beyond what you can do with custom format strings.

But the code I've written is so gross I thought I would ask anyway.

What I need is for a decimal to be displayed as either a 6 or 7 digit string, like so:

number = 12345.67M
(optional)
tenthousands thousands hundreds tens ones tenths hundredths
     1          2         3      4    5     6        7

Here's the code I've written to achieve this:

public static string ConvertDecimalToString(decimal easting, int length)
{
    var formatString = "{0:0000.00}";
    var numberAsString = string.Format(formatString, easting);
    var removePeriod = numberAsString.Replace(".", "");

    if (removePeriod.Length > length)
    {
        return removePeriod.Substring(removePeriod.Length - length, length);
    }
    else
    {
        return removePeriod.PadLeft(length, '0');
    }
}

Expected inputs and outputs:

Input           Output(6)    Output(7)
912345.67M      234567       1234567
12345.67M       234567       1234567
1234.56M        123456       0123456
1234.5M         123450       0123450
1234M           123400       0123400
234M            023400       0023400

回答1:

If you want a decimal 12345.67displayed as 1234567 (just omit the decimal point) use this trick:

decimal number = 12345.67M;
string s = string.Format("{0:0000000}", number * 100.0);

Or

string s = string.Format("{0:F0}", number * 100.0); // zero decimal places

Morale: Do not fiddle with a string produced from formatting, modify the input value instead and let the formatting do its job.



回答2:

If i understand you correctly, you want to separate your number to digits

str=number.ToSting() will give a string you can iterate and create your number

str.split('.') will give you both sides of the number Then you will be able to build your stribg number dynamicly without forcing a format