# javascript 如何实现保留两位小数(不四舍五入)

liuj4
• 26

12.19888 => 12.19
12 => 12.00

##### 9个回答
``````function getResult (a) {
return (Math.floor(a * 100) / 100).toFixed(2)
}``````

``const clip = num => Number(parseFloat(num).toFixed(3).slice(0, -1));``
``````(~~(12.19888 * 100) / 100).toFixed(2);
(~~(12 * 100) / 100).toFixed(2);``````

toFixed(2)

``````Math._trunc = [
(num, dig) => { // 字符串模拟
const [ int, dec ] = (num + ".").toString().split(".")
return int + "." + (dec + "0".repeat(dig)).substring(0, dig)
},
(num, dig) => { // 正常解法
const pow = 10 ** dig
return (Math.trunc(num * pow) / pow).toFixed(dig)
},
(num, dig) => { // 干掉四舍五入
const res = num.toFixed(dig)
return (num * 10 ** dig * 10 % 10 >= 5) ? (res - 0.1 ** dig).toString() : res
}
][ parseInt(Math.random() * 10) % 3 ]

Number.prototype.trunc = function (dig = 2, str) {
const s = Math._trunc(this, dig)
return str ? s : + s
}

(12).trunc(2) // 12
(12.9888).trunc(2) // 12.98
(12).trunc(2, true) // "12.00"
``````
``````str.toString().includes(".")?getResult(str.toString()):str+".00";
function getResult(str){
return str.split(".")[1].length>1?str.substring(0,str.length-2 ):str+"0";
}
``````

1、先把数值转为小数形式，并补充到4位小数
2、使用substr截取要的个数即可

``````var num = 12.99999999;
num = parseFloat(num).toString().split('.');
var numInt = num[0];
var numDec = num[1];

var target = `\${numInt}.\${numDec ? numDec.substr(0,2) : '00'}`;
console.log(target);``````

``````let num=12.12378;
let arr=parseInt(num*100).toString().split('')
arr.splice(-2,0,'.')
let str=arr.join('')``````
``let fn = n => parseInt(n * 100) / 100``
##### 撰写回答
###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进