格式化双精度值以适应最大字符串大小 [英] Format a double value to fit into a maximum string size

查看:29
本文介绍了格式化双精度值以适应最大字符串大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要格式化一个双精度值,使其适合 13 个字符的字段.有没有办法用 String.Format 做到这一点,还是我坚持逐个字符的工作?

I need to format a double value so that it fits within a field of 13 characters. Is there a way to do this with String.Format or am I stuck with character-by-character work?

(希望他们这次能留下来)

Edits: (hopefully they will stay this time)

案例超过一万亿,我要报告错误.它基本上是一个计算器界面.

With cases greater than a trillion I am to report an error. It's basically a calculator interface.

我自己的回答:

private void DisplayValue(double a_value)
{
    String displayText = String.Format("{0:0." + "".PadRight(_maxLength, '#') + "}", a_value);

    if (displayText.Length > _maxLength)
    {
        var decimalIndex = displayText.IndexOf('.');
        if (decimalIndex >= _maxLength || decimalIndex < 0)
        {
            Error();
            return;
        }

        var match = Regex.Match(displayText, @"^-?(?<digits>\d*)\.\d*$");
        if (!match.Success)
        {
            Error();
            return;
        }

        var extra = 1;
        if (a_value < 0)
            extra = 2;

        var digitsLength = match.Groups["digits"].Value.Length;
        var places = (_maxLength - extra) - digitsLength;

        a_value = Math.Round(a_value, places);

        displayText = String.Format("{0:0." + "".PadRight(_maxLength, '#') + "}", a_value);

        if (displayText.Length > _maxLength)
        {
            Error();
            return;
        }
    }

    DisplayText = displayText;
}

推荐答案

如果这是计算器,那么您不能使用您在问题中提到的逐字符方法.您必须先将数字四舍五入到所需的小数位,然后才显示它,否则可能会得到错误的结果.例如,将数字 1.99999 修剪为 4 的长度将是 1.99,但结果 2 会更正确.

If this is calculator, then you can not use character-by-character method you mention in your question. You must round number to needed decimal places first and only then display it otherwise you could get wrong result. For example, number 1.99999 trimmed to length of 4 would be 1.99, but result 2 would be more correct.

以下代码将满足您的需求:

Following code will do what you need:

int maxLength = 3;
double number = 1.96;
string output = null;
int decimalPlaces = maxLength - 2; //because every decimal contains at least "0."
bool isError = true;

while (isError && decimalPlaces >= 0)
{
    output = Math.Round(number, decimalPlaces).ToString();
    isError = output.Length > maxLength;
    decimalPlaces--;
}

if (isError)
{
    //handle error
}
else
{
    //we got result
    Debug.Write(output);
}

这篇关于格式化双精度值以适应最大字符串大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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