Home  >  Article  >  Web Front-end  >  2 custom functions to retain two decimal places in JavaScript_javascript tips

2 custom functions to retain two decimal places in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:49:541201browse

For some floating-point numbers with multiple digits after the decimal point, we may only need to reserve 2 digits, but js does not provide such a direct function, so we have to write our own function to implement this function. The code is as follows:

Copy code The code is as follows:

function changeTwoDecimal(x) {
var f_x = parseFloat(x);
if (isNaN(f_x)) {
alert('function:changeTwoDecimal->parameter error');
return false;
}
var f_x = Math.round(x * 100 ) / 100;
Return f_x;
}

Function: Round the floating point number to 2 decimal places Usage: changeTwoDecimal(3.1415926) returns 3.14 changeTwoDecimal(3.1475926) returns 3.15


js retains 2 decimal places (mandatory)

For decimal places greater than 2 digits, it is no problem to use the above function, but if it is less than 2 digits, such as: changeTwoDecimal(3.1), it will return 3.1. If you must need a format like 3.10, then you need the following This function:

Copy code The code is as follows:

function changeTwoDecimal_f(x) {
var f_x = parseFloat(x);
if (isNaN(f_x)) {
alert('function:changeTwoDecimal->parameter error');
return false;
}
var f_x = Math.round(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; String format usage: changeTwoDecimal(3.1415926) returns 3.14 changeTwoDecimal(3.1) returns 3.10
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn