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

问题描述 投票:0回答:5

我正在开发一个 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);
}
javascript math decimal
5个回答
9
投票

还没有测试过:

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
投票

那又如何

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

查看这里


1
投票

虽然

pow(10,precision-scale) - pow(10,-scale)
是正确的公式,但您需要使用小数类型而不是浮点数来计算它。

例如,如果 precision=4,scale=5,如果用 float 计算的话,你会得到

0.09999000000000001

因此,在Python中,你可以这样做:

from decimal import Decimal

def calculate_decimal_range(precision: int, scale: int) -> Decimal:    
    precision, scale = Decimal(precision), Decimal(scale)
    return 10**(precision-scale) - 10**-scale

0
投票

我会做一些类似的事情

((10 * pintPrecision) - 1) + "." + ((10 * pintScale) - 1)


0
投票

正如Guangyang Li他的回答中指出的那样,在javascript中进行计算的数学灵魂可能会导致浮点不准确的问题,因为javascript没有十进制类型的概念。

相反,您应该使用字符串机制来处理这个问题,就像您最初的尝试一样。
这是一种更短、更有效的方法,可以复制 9 来构建结果:

function maxDecimalValue(precision, scale) {
    var strMaxValue = (new Array(precision - scale + 1).join('9') + '.' +  new Array(scale + 1).join('9'));
    return parseFloat(strMaxValue);
}

console.log(5, 2, maxDecimalValue(5,2)); 
console.log(7, 5, maxDecimalValue(7,5)); 

受到有关复制字符问题的回答的启发

© www.soinside.com 2019 - 2024. All rights reserved.