Js floating point Numbers keep two decimal point sample code of rounding
- 2020-03-30 01:03:32
- OfStack
var changeTwoDecimal_f= function (floatvar){
var f_x = parseFloat(floatvar);
if (isNaN(f_x)){
return '0.00';
}
var f_x = Math.round(f_x*100)/100;
var s_x = f_x.toString();
var pos_decimal = s_x.indexOf('.');
if (pos_decimal < 0){
pos_decimal = s_x.length;
s_x += '.';
}
while (s_x.length <= pos_decimal + 2){
s_x += '0';
}
return s_x;
}
Js provides a rounding function:
js Round the function toFixed (), the parameter inside I'm just keeping the number of decimal places.
<script language="javascript">
document.write("<h1>JS Keep the two decimal examples </h1><br>");
var a=2.1512131231231321;
document.write(" Original value: "+a+"<br>");
document.write(" Two decimal places :"+a.toFixed(2)+"<br> Four digit decimal point "+a.toFixed(4));
</script>