Javascript 将任意数字填入12位

Javascript 将任意数字填入12位,javascript,numbers,Javascript,Numbers,我正在使用.eval()获取一个数字,但我需要将数字放入一个只有12位数字的空间,我希望能够在始终显示12位数字的地方进行舍入。我原以为.toExponential()可以解决这个问题,但它的值通常也超过12位。我当前的代码如下所示- function enter() { string = eval(string); console.log(string.toExponential()); if (string.toString().length > 12) { str

我正在使用.eval()获取一个数字,但我需要将数字放入一个只有12位数字的空间,我希望能够在始终显示12位数字的地方进行舍入。我原以为.toExponential()可以解决这个问题,但它的值通常也超过12位。我当前的代码如下所示-

function enter() {
  string = eval(string);
  console.log(string.toExponential());
  if (string.toString().length > 12) {
    string = string.toExponential();
    updateDisplay();
  } else {
    updateDisplay();
  }
}

有什么办法可以解决这个问题吗?

这个问题可能有一些很好的答案,但这就是我读了你的问题后想到的

首先将no转换为sting

function enter(no)
{
var x=no.toString();
var newnum=x.substring(0,11);
//check for roundoff 
if (Number(x.substring(12))>5)
newnum=Number(newnum)+1;
else 
newnum=Number(newnum);
return newnum;
}

另一个选项是将数字压缩为另一个
基数

这将需要在计算字符串时调用
解压
,但它将允许您在较小的点中拟合较大的数字

功能压缩编号(编号){
返回编号。toString(36);
}
函数解压缩编号(编号){
返回parseInt(数字36);
}
//试验
控制台日志(“基本编号”,5,压缩编号(5));
log('Base 16 example',15,compressNumber(15));
log('A“1”后跟11个零,Math.pow(10,11),compressNumber(Math.pow(10,11));
log('A“1”后跟11个零,负',-Math.pow(10,11),compressNumber(-Math.pow(10,11));
log('A“1”后跟11个零,解压缩',Math.pow(10,11),decompressNumber(compressNumber(Math.pow(10,11)));
console.log('最大的12位压缩数字',Math.pow(10,11).toString().replace(/\d/ig,'z'));

console.log('解压后的最大12位压缩数',解压数(Math.pow(10,11).toString().replace(/\d/ig,'z'))为什么要使用eval来获取号码。。。字符串是在其他地方定义的,对任意输入求值允许代码注入。无论您想实现什么,您都无法将13位数字转换为12位而不丢失任何内容。