可能这与之前提出的问题重复,但我找不到答案。 我正在使用javascript并尝试显示数字p1 * 10 ^ p2,其中p1是正整数,p2是整数(负数或正数)。 不幸的是,由于数字的二进制表示,以下函数不起作用。
function toDisplay(p1, p2) {return p1*Math.pow(10, p2);}
它通常会返回一个长十进制数,这只是我需要的确切形式的近似值。有人可以帮我修改这个功能吗?我需要的是将p1中的小数点移动p2个位置(向左或向右,取决于p2的符号)并根据需要添加0。我需要一个字符串作为答案。我试图这样做,但我无法弄清楚如何使它工作。 任何帮助将不胜感激。
答案 0 :(得分:0)
由于您处理10的幂,并且您只关心以十进制显示它们,这将起作用:
function repeatStr(s, n){
// returns s, repeated n times.
if(String.prototype.repeat){
return s.repeat(n);
}
var res = "";
for(var i=0; i<n; i++){
res += s;
}
return res
}
function getDecimal(p1, p2) {
// returns the decimal representation, as a string, of p1*10^p2.
p1 = p1.toString();
if (p2 === 0) {
return p1 //p1*10^0 == p1*1 == p1.
}
if(p2 > 0) {
// multiplying by 10^p2 just adds p2 0's.
return p1 + repeatStr("0", p2);
} else {
// p1 is negative, so we have (-p2)-1 0's after the decimal point.
return "0." + repeatStr("0", (p2*-1) - 1) + p1;
}
}
答案 1 :(得分:0)
尝试Math.round(number * 100000) / 100000
答案 2 :(得分:0)
好吧,希望你不要讨厌eval
function toDisplay(p1, p2) {
return eval(p1 + 'e' + p2);
}
返回一个浮点数。您可以+ ""
将其设为字符串。