1. 程式人生 > >取小數點後幾位寫法比較

取小數點後幾位寫法比較

1、 返回float

var a = 123.3167795010225;
var data_s = new Date();
for (var i = 0; i < 10000; i++) {
	var b = Math.round(a * 1000000) / 1000000;
}
var data_e = new Date();
console.log(data_s - data_e);


var data_s = new Date();
for (var i = 0; i < 10000; i++) {
	var b = parseFloat(a.toFixed(6));
}
var data_e = new Date();
console.log(data_s - data_e);

VM3954:7 -2
VM3954:15 -7

var a = 123.3167795010225;
var data_s = new Date();
for (var i = 0; i < 100000; i++) {
	var b = Math.round(a * 1000000) / 1000000;
}
var data_e = new Date();
console.log(data_s - data_e);


var data_s = new Date();
for (var i = 0; i < 100000; i++) {
	var b = parseFloat(a.toFixed(6));
}
var data_e = new Date();
console.log(data_s - data_e);

VM3957:7 -4
VM3957:15 -42
var a = 123.3167795010225;
var data_s = new Date();
for (var i = 0; i < 100000; i++) {
	var b = Math.round(a * 10000000000) / 10000000000;
}
var data_e = new Date();
console.log(data_s - data_e);


var data_s = new Date();
for (var i = 0; i < 100000; i++) {
	var b = parseFloat(a.toFixed(10));
}
var data_e = new Date();
console.log(data_s - data_e);

VM3960:7 -4
VM3960:15 -50

三次比較得出Math.round( a * 1000000) / 1000000) 效能更優

2、 返回String

var a = 123.3167795010225;
var data_s = new Date();
for (var i = 0; i < 100000; i++) {
	var b = Math.round(a * 10000000000) / 10000000000 + '';
}
var data_e = new Date();
console.log(data_s - data_e, b);


var data_s = new Date();
for (var i = 0; i < 100000; i++) {
	var b = a.toFixed(10);
}
var data_e = new Date();
console.log(data_s - data_e, b);

VM3969:7 -3 "123.316779501"
VM3969:15 -34 "123.3167795010"
綜上所述,toFixed效能差,少用