Javascript 使用比例和精度计算小数点的最大值
我正在开发一个JavaScript函数,它有两个值:十进制值的精度和十进制值的小数位数 此函数应计算可存储在该大小的十进制中的最大值 例如:精度为5且刻度为3的小数点的最大值为99.999 我的工作做得很好,但并不优雅。有人能想出更聪明的办法吗 另外,请原谅使用这种奇怪的匈牙利符号Javascript 使用比例和精度计算小数点的最大值,javascript,math,decimal,Javascript,Math,Decimal,我正在开发一个JavaScript函数,它有两个值:十进制值的精度和十进制值的小数位数 此函数应计算可存储在该大小的十进制中的最大值 例如:精度为5且刻度为3的小数点的最大值为99.999 我的工作做得很好,但并不优雅。有人能想出更聪明的办法吗 另外,请原谅使用这种奇怪的匈牙利符号 function maxDecimalValue(pintPrecision, pintScale) { /* the maximum integers for a decimal is equal to t
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);
}
函数maxDecimalValue(pintPrecision,pintScale){
/*小数点的最大整数等于精度-小数位数。
小数点后的最大位数等于刻度。
例如,十进制(5,3)的最大值为99.999
*/
//必须有一个更优雅的方式来做到这一点。。。
变量intMaxInts=(pintPrecision-pintScale);
var intMaxDecs=品级;
var计数;
var strMaxValue=“”;
//构建最大值。从整数开始。
如果(intMaxInts==0)strMaxValue=“0”;
对于(intCount=1;intCount 0){
strMaxValue+=”;
对于(intCount=1;intCount我会按照((10*pintPrecision)-1)+“+((10*pintScale)-1)
做些什么呢
function maxDecimalValue(pintPrecision, pintScale)
{
var result = "";
for(var i = 0; i < pintPrecision; ++i)
{
if(i == (pintPrecision - pintScale)
{
result += ".";
}
result += "9";
}
return parseFloat(result);
}
函数maxDecimalValue(pintPrecision,pintScale)
{
var结果=”;
对于(变量i=0;i
查看它尚未测试它:
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的原始答案之后,我也得出了这个结论。谢谢你的确认!