[英]Parse to float with 2 decimal places
I need to round a value with 2 decimal places that I receive from a web service. 我需要将一个从Web服务接收的值四舍五入为2个小数位。 To do this i use this methods toFixed and parseFloat because I need the final value in a float.
为此,我使用此方法toFixed和parseFloat,因为我需要浮点数中的最终值。 However when I have this value "5.5000000" he shows me the value with only one decimal place "5.5"...
但是,当我的值是“ 5.5000000”时,他会向我显示该值仅带小数点后一位的“ 5.5” ...
I did in that way: 我是这样做的:
var num = 5.5000000;
var n = num.toFixed(2);
var numFinal = parseFloat(n);
您必须在parseFloat
之后调用toFixed
:
parseFloat(yourString).toFixed(2)
You can do something like this 你可以做这样的事情
/**
* Convert the value to the Number with the precision.
* @param {Number} value value to be converted
* @param {Number} [precision=0] number of decimal places
* @returns {Number} converted number.
*/
function toNumber (value, precision) {
precision = precision || 0;
if (precision === 0) {
return value * 1;
} else {
return Number((value * 1).toFixed(precision));
}
}
Short Answer : There is no way in JS to have Number datatype value with trailing zeros after a decimal. 简短的回答 :JS中没有办法让Number数据类型的值在小数点后尾随零。
Long Answer : Its the property of toFixed or toPrecision function of JavaScript, to return the String. 长答案 :JavaScript的toFixed或toPrecision函数的属性,以返回String。 The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype.
原因是Number数据类型不能具有a = 2.00之类的值,它将始终删除小数点后的零。这是Number数据类型的内置属性。 So to achieve the above in JS we have 2 options
因此,要在JS中实现上述目标,我们有2个选择
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.