JavaScript preserves 2 custom functions with two decimal digits _javascript tips

Source: Internet
Author: User

For some decimal point after a number of floating-point numbers, we may only need to retain 2 bits, but JS does not provide such a direct function, so we have to write the function to implement this function, the code is as follows:

Copy Code code 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: Rounding floating-point numbers, taking the 2-bit usage after the decimal point: Changetwodecimal (3.1415926) returns 3.14 Changetwodecimal (3.1475926) returns 3.15


JS retains 2 decimal places (mandatory)

For decimal digits greater than 2 digits, use the above function is OK, but if less than 2 bits, such as: Changetwodecimal (3.1), will return 3.1, if you must need a format such as 3.10, then you need the following function:

Copy code code 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: Rounding floating-point numbers, taking 2 digits after the decimal point, or 0 if less than 2 digits,
This function returns the format usage of the string: 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.