2016-04-26 120 views
2

toFixed方法我有一些var x = 2.305185185185195;没有四舍五入到五位数

x = x.toFixed(5); 

x = 2.30519但我需要这个没有即四舍五入2.30518

我读了一些线索保留两位小数,但无法找到五个小数地方。

任何帮助,将不胜感激。

+0

的可能的复制[显示两个小数位,没有舍入(http://stackoverflow.com/questions/4187146/display-two-decimal-places-no-舍入) – Pietro

回答

4

您可以使用适当的因子并将其放回并返回除法结果。

基本上这个解决方案将点向左移动10^d的因子并获得一个整数,并将值与前一个因子相除以得到正确的数字。

function getFlooredFixed(v, d) { 
 
    return (Math.floor(v * Math.pow(10, d))/Math.pow(10, d)).toFixed(d); 
 
} 
 

 
var x = 2.305185185185195; 
 

 
document.write(getFlooredFixed(x, 5));

+2

完美,+10 !!!! –

+0

你可以添加几行解释吗? '使用读卡器:) – guradio

+0

https://jsfiddle.net/L00g8bwj/1/'slice()'用nums <1.000快3倍,用数字<1.000.000快7倍...('slice() 'work time ='const',它不依赖于数字) –

2
var x = 2.305185185185195 + ''; // make it string 

console.log(x.slice(0, x.indexOf('.') + 6)); // 6 = '.' + 5 digits