使用比例和精度计算小数的最大值

时间:2012-01-05 21:07:53

标签: javascript math decimal

我正在研究一个带有两个值的JavaScript函数:十进制值的精度和&十进制值的比例。

此函数应计算可以以该大小的十进制值存储的最大值。

例如:精度为5且标度为3的小数的最大值为99.999。

我所做的工作,但并不优雅。谁能想到更聪明的东西?

另外,请原谅使用这种古怪的匈牙利表示法。

function maxDecimalValue(pintPrecision, pintScale) {
    /* the maximum integers for a decimal is equal to the precision - the scale.
        The maximum number of decimal places is equal to the scale.
        For example, a decimal(5,3) would have a max value of 99.999
    */
    // There's got to be a more elegant way to do this...
    var intMaxInts = (pintPrecision- pintScale);
    var intMaxDecs = pintScale;

    var intCount;
    var strMaxValue = "";

    // build the max number.  Start with the integers.
    if (intMaxInts == 0) strMaxValue = "0";    
    for (intCount = 1; intCount <= intMaxInts; intCount++) {
        strMaxValue += "9";
    }

    // add the values in the decimal place
    if (intMaxDecs > 0) {
        strMaxValue += ".";
        for (intCount = 1; intCount <= intMaxDecs; intCount++) {
            strMaxValue += "9";
        }
    }
    return parseFloat(strMaxValue);
}

3 个答案:

答案 0 :(得分:5)

尚未测试过:

function maxDecimalValue(precision, scale) {
    return Math.pow(10,precision-scale) - Math.pow(10,-scale);
}

精度必须为正

maxDecimalValue(5,3) = 10^(5-3) - 10^-3 = 100 - 1/1000 = 99.999
maxDecimalValue(1,0) = 10^1 - 10^0 = 10 - 1 = 9
maxDecimalValue(1,-1) = 10^(1+1) - 10^1 = 100 - 10 = 90
maxDecimalValue(2,-3) = 10^(2+3) - 10^3 = 100000 - 1000 = 99000

答案 1 :(得分:1)

怎么样?
function maxDecimalValue(pintPrecision, pintScale)
{
    var result = "";
    for(var i = 0; i < pintPrecision; ++i)
    {
        if(i == (pintPrecision - pintScale)
        {
            result += ".";
        }
        result += "9";
    }
    return parseFloat(result);
}

查看here

答案 2 :(得分:0)

我会按照((10 * pintPrecision) - 1) + "." + ((10 * pintScale) - 1)

的方式做点什么
相关问题