【问题标题】:Calculating the maximum value for a decimal using scale and precision使用比例和精度计算小数的最大值
【发布时间】:2012-02-03 17:02:41
【问题描述】:

我正在研究一个接受两个值的 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


    【解决方案1】:

    没有测试过:

    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
    

    【讨论】:

    • 在 dnc253 的原始答案之后,我最终也想出了这个。感谢您的确认!
    【解决方案2】:

    怎么样

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

    看看here

    【讨论】:

    • 此方案不支持精度小于刻度的情况,因此您可能需要添加另一个 if 语句。
    【解决方案3】:

    我会按照((10 * pintPrecision) - 1) + "." + ((10 * pintScale) - 1) 的方式做一些事情

    【讨论】:

      【解决方案4】:

      虽然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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-02
        • 1970-01-01
        • 1970-01-01
        • 2015-10-29
        相关资源
        最近更新 更多