2017-03-16 90 views
0

我使用.eval()获取数字,但我需要将数字合并到只有十二位数字适合的空间中,我希望能够在那里圆角将始终显示十二位数字。我认为.toExponential()可以解决这个问题,但是通常这些值也会长于12位数。我目前的代码是这样的 -将任意数字合并为12位数字

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

任何方式来处理这个?

+1

为什么你使用eval获得数量在所有...串在其他地方定义,并evaling任意输入允许代码注入。 –

+0

无论你想达到什么目的,都无法将13位数字放入12位而不会有任何损失。 – n00dl3

回答

1

有可能是这个问题的一些很好的答案,但是这是读你的问题

首先转换没有刺痛后出现什么在我的脑海里。

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; 
} 
0

另一种选择可能是将数字压缩到另一个radix

这将需要一个decompress调用时评估字符串,但它可以让你适应更大的数字在更小的点。

function compressNumber(number) { 
 
    return number.toString(36); 
 
} 
 

 
function decompressNumber(number) { 
 
    return parseInt(number, 36); 
 
} 
 
//Test 
 
console.log("Basic number", 5, compressNumber(5)); 
 
console.log('Base 16 example', 15, compressNumber(15)); 
 
console.log('A "1" followed by 11 zeroes', Math.pow(10, 11), compressNumber(Math.pow(10, 11))); 
 
console.log('A "1" followed by 11 zeroes, negative', -Math.pow(10, 11), compressNumber(-Math.pow(10, 11))); 
 
console.log('A "1" followed by 11 zeroes, decompressing', Math.pow(10, 11), decompressNumber(compressNumber(Math.pow(10, 11)))); 
 
console.log('Biggest 12 digit compressed number', Math.pow(10, 11).toString().replace(/\d/ig, 'z')); 
 
console.log('Biggest 12 digit compressed number decompressed', decompressNumber(Math.pow(10, 11).toString().replace(/\d/ig, 'z')));

相关问题