Js retains two decimal places. js retains two decimal places.

Source: Internet
Author: User
Tags rounds

Js retains two decimal places. js retains two decimal places.

This article is a small EditorJs retains two decimal placesThis is a classic problem that people often encounter. It lists the function writing methods and analysis of problems in various situations. The following is all about it:

I. First, let's start with the classic "Rounding" algorithm.
Var num = 2.446242342; num = num. toFixed (2); // The output result is 2.45.
2. No rounding

First, add the decimal side integer:

Math. floor (15.7784514000*100)/100 // The output result is 15.77.

Second, use regular expression matching as a string:

Number (15.7784514000.toString (). match (/^ \ d + (? : \. \ D {0, 2 })? //) // The output result is 15.77, which cannot be used as an integer. For example, 10 must be written as 10.0000.

NOTE: If it is a negative number, convert it to a positive number before calculation, and then convert it back to a negative number.

Another classic solution is to retain two decimal places in js after rounding:

// Two decimal places (if the second decimal point is 0, one decimal point is retained) function keepTwoDecimal (num) {var result = parseFloat (num ); if (isNaN (result) {alert ('parameter passed error, please check! '); Return false;} result = Math. round (num * 100)/100; return result;} // rounded to keep two decimal places (0 is used as a substitute if the number is not enough) function keepTwoDecimalFull (num) {var result = parseFloat (num); if (isNaN (result) {alert ('parameter passing error, please check! '); Return false;} result = Math. round (num * 100)/100; var s_x = result. 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 ;}

Ii. Method for Js to take the float type and the second digit after the decimal point
<Script type = "text/javascript"> // retain two decimal places // function: rounds a floating point number to the nearest decimal place) {var f = parseFloat (x); if (isNaN (f) {return;} f = Math. round (x * 100)/100; return f;} // The system retains two decimal places. For example, 2 will add 00 after 2. that is, 2.00 function todecimal (x) {var f = parseFloat (x); if (isNaN (f) {return false;} var f = Math. round (x * 100)/100; var s = f. toString (); var rs = s. indexOf ('. '); if (rs <0) {rs = s. length; s + = '. ';} while (s. length <= rs + 2) {s + = '0';} return s;} function fomatFloat (src, pos) {return Math. round (src * Math. pow (10, pos)/Math. pow (10, pos);} // rounded to alert ("retain 2 decimal places:" + toDecimal (3.14159267); alert ("force keep 2 decimal places: "+ toDecimal (3.14159267); alert (" retain 2 decimal places: "+ toDecimal (3.14559267); alert (" force keep 2 decimal places: "+ todecimal (3.15159267); alert (" retain 2 decimal places: "+ fomatFloat (3.14559267, 2); alert (" retain 1 decimal places: "+ fomatFloat (3.15159267, 1); // five homes six into alert ("retain 2 decimal places:" + 1000.003.toFixed (2); alert ("retain 1 decimal places: "+ 1000.08.toFixed (1); alert (" retain 1 decimal point: "+ 1000.04.toFixed (1); alert (" retain 1 decimal point: "+ 1000.05.toFixed (1 )); // scientific count alert (3.1415.toExponential (2); alert (3.1455.toExponential (2); alert (Clerk (2); alert (3.1465.toExponential (2 )); alert (3.1665.toExponential (1); // precise to n digits, not including n digits alert ("precise to 2nd decimal places" + 3.1415.toPrecision (2 )); alert ("accurate to 3rd decimal places" + 3.1465.toPrecision (3); alert ("accurate to 2nd decimal places" + 3.1415.toPrecision (2 )); alert ("accurate to 2nd decimal places" + 3.1455.toPrecision (2); alert ("accurate to 5th decimal places" + 3.141592679287.toPrecision (5); </script>

Use Javascript to get the first two digits of the float decimal point. For example, 22.127456 is used to get 22.13. How can this problem be solved?

1. Discard the fractional part and retain the integer part.

parseInt(5/2)

2. rounded up. If there is a decimal number, add 1 to the integer part.

Math.ceil(5/2)

3. rounding.

Math.round(5/2)

4. Round down

Math.floor(5/2)

Alternative Method

1. the most stupid way

function get(){  var s = 22.127456 + "";  var str = s.substring(0,s.indexOf(".") + 3);  alert(str);}

2. The regular expression works well.

<script type="text/javascript">onload = function(){  var a = "23.456322";  var aNew;  var re = /([0-9]+.[0-9]{2})[0-9]*/;  aNew = a.replace(re,"$1");  alert(aNew);}</script>

3. He is smart.

<script>var num=22.127456;alert( Math.round(num*100)/100);</script>

4. Friends who will use fresh things... but IE5.5 + is required.

5. 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:

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;}
3. Javascript retains two decimal places and automatically adds zero points.
function returnFloat(value){ var value=Math.round(parseFloat(value)*100)/100; var xsd=value.toString().split("."); if(xsd.length==1){ value=value.toString()+".00"; return value; } if(xsd.length>1){ if(xsd[1].length<2){ value=value.toString()+"0"; } return value; }}
4. JS is an integer, js is an absolute value, and js is rounded to the nearest integer (two decimal places can be retained)

JS gets an integer, js gets the absolute value, and js rounding (two decimal places can be retained) functions are as follows:

<SCRIPT language = javascript> <! -- Function jsMath () {document. write (Math. floor (5.80) + "<br>"); // rounded up or down to document. write (Math. round (5.80) + "<br>"); // rounding, taking the integer document. write (Math. round (5.80*100)/100) + "<br>"); // rounding, retain two decimal places document. write (Math. ceil (5.10) + "<br>"); // rounds the document. write (Math. abs (-5.80) + "<br>"); // take the absolute value document. write (Math. max () + "<br>"); // returns the largest document of the two values. write (Math. min (55,58) + "<br>"); // returns the highest decimal number among the two values} --> </SCRIPT> <div> <script> jsMath (); </script> </div>
Summary

JS data formatting is a common problem in front-end web development. Especially when the data type is Float, special processing is required, for example, whether two decimal places are retained and whether the decimal point data needs to be rounded in. The following describes how to format and retain two decimal places.

1. JS built-in method toFixed (). The toFixed () method rounds the Number to a Number with a specified decimal place.

Syntax: NumberObject. toFixed (num), mun is a required parameter, that is, the number of digits of the specified decimal number, which is 0 ~ Values between 20, including 0 and 20. Some implementations support a larger value range. If this parameter is omitted, it is replaced by 0. Therefore, the toFixed () method can retain 2 bits, 3 bits, and 4 bits, depending on the num value.

Return Value: return the string representation of NumberObject. If no exponential notation is used, there is a fixed num digit after the decimal point. If necessary, the number is rounded off, or 0 can be used to make up for the specified length. If num is greater than le + 21, this method only calls NumberObject. toString () and returns the string represented by exponential notation.

When num is too small or too large, an exception RangeError is thrown. 0 ~ The value between 20 does not cause this exception. Some implementations support values in a larger or smaller range.

If the object that calls this method is not a Number, a TypeError error is thrown.

<Script type = "text/javascript"> var num = new Number (13.376954); document. write (num. toFixed (2) </script> output: 13.38

2. the user-defined function is used to retain decimal places and rounding them out.

Function roundFun (numberRound, roundDigit) {// rounding, the number of reserved digits is roundDigitif (numberRound> = 0) {var tempNumber = parseInt (numberRound * Math. pow (10, roundDigit) + 0.5)/Math. pow (10, roundDigit); return tempNumber;} else {numberRound1 =-numberRound; var tempNumber = parseInt (numberRound1 * Math. pow (10, roundDigit) + 0.5)/Math. pow (10, roundDigit); return-tempNumber ;}}

Then you can call the roundFun () function. For example, roundFun ('13. 376954 ', 2); of course, the returned result is the same as that of the first method.

3. The number of digits after the decimal point is intercepted by the function. Of course, this method is not rounded down.

<script type=”text/javascript”>tmp = 13.376954″result = tmp.substr(0,tmp.indexOf(“.”)+2);alert(result);</script>

The above is a summary of how JavaScript retains two decimal places. Thanks for your support. If you keep two decimal places in Javascript, there is nothing you don't understand, you can discuss it in the message area below.

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.