【发布时间】: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