使用小数位数和精度计算小数的最大值
Calculating the maximum value for a decimal using scale and precision
我正在开发一个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);
}
尚未测试:
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
怎么样
function maxDecimalValue(pintPrecision, pintScale)
{
var result = "";
for(var i = 0; i < pintPrecision; ++i)
{
if(i == (pintPrecision - pintScale)
{
result += ".";
}
result += "9";
}
return parseFloat(result);
}
在这里查看
我会按照((10 * pintPrecision) - 1) + "." + ((10 * pintScale) - 1)
的思路做一些事情
尽管pow(10,precision-scale) - pow(10,-scale)
是正确的公式,但您需要使用十进制类型而不是浮点类型来计算它。
例如,如果精度=4,小数位数=5,则如果使用浮点计算,则会得到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
相关文章:
- 货币代码为欧元-金额的格式不应包含小数
- 根据元素和容器大小计算边距
- 从Rally获取一个特定的标记,以便计算另一个字段中的值
- 使用D3.js计算带有字母间距的文本长度
- 使用CSS或JavaScript计算分页符的数量
- 可以't计算自定义谷歌地图的js
- 用小数计算日期之间的天数
- 用小数计算解析
- 计算字符串中的句子数,同时在 JavaScript 中考虑小数
- 如何在javascript中计算小数
- 复杂数学计算中的舍入小数
- 此计算中小数位数的右Javascript代码
- 使用小数位数和精度计算小数的最大值
- Javascript计算以0开头的数字为小数
- 没有小数的数据循环的Javascript计算
- 字符串计算的小数
- 使计算包括小数
- 使用Javascript进行计算,无需对小数进行舍入
- 如何在JavaScript中计算零小数位数
- 数学输入,计算和输出Javascript与分数/小数