JavaScript retains two udfs with two decimal places

Source: Internet
Author: User
Tags rounds

For floating point numbers with multiple digits after decimal points, we may only need to retain two digits, but js does not provide such a direct function. Therefore, we have to write the function to implement this function by ourselves. The Code is as follows:
Copy codeThe 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: rounds a floating point number to the second place after the decimal point. Usage: changeTwoDecimal (3.1415926) returns 3.14 changeTwoDecimal (3.1475926) and 3.15


Js retains 2 decimal places (mandatory)

If the number of decimal places is greater than 2 digits, the above function is no problem, but if it is less than 2 digits, for example: changeTwoDecimal (3.1), 3.1 is returned, if you must use the format 3.10, you need the following function:
Copy codeThe 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;
}

Function: rounds a floating point number to the second place after the decimal point. If there are less than two digits, add 0,
This function returns the string format usage: changeTwoDecimal (3.1415926) returns 3.14 changeTwoDecimal (3.1) returns 3.10

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.