固定精度且无句点的十进制自定义格式字符串 [英] decimal custom format string with fixed precision and no period

查看:94
本文介绍了固定精度且无句点的十进制自定义格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一种情况,我认为您无法使用自定义格式字符串.

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.

我需要的是将小数点显示为6或7位数字的字符串,如下所示:

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

推荐答案

如果您想将小数12345.67显示为1234567(只需省略小数点),请使用以下技巧:

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

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.

这篇关于固定精度且无句点的十进制自定义格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆