JavaScript implements several methods to preserve two decimal places

Source: Internet
Author: User
Tags pow

This article mainly introduces the implementation of JavaScript to preserve two decimal places of several methods, if the number of the original decimal places less than two, then the lack of automatic 0, interested in the small partners can refer to

The first method: The JavaScript implementation retains a two-bit decimal one-digit auto-complement 0 code instance:
The first method describes how to achieve the number of two-bit decimal effect, if the number of the original scale of less than two bits, then the lack of automatic 0, which is also for the unified effect, first look at the code example:

?
12345678910111213141516 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; }}var num=3.1;console.log(returnFloat(num));

The above code implements our requirements, the following describes its implementation process.
Code Comment:
1.function Returnfloat (value) {}, the parameter is the number to be converted.
2.var value=math.round (parsefloat (value) *100)/100, which should be at the heart of the function, parsefloat (value) converts the argument to a floating-point number, because the argument is likely to be a string, Multiply by 100 because you want to keep two decimal places, first move the decimal point to the right two digits, and then use the Math.Round () method to apply rounding calculation, and finally divided by 100, so that the retention of two decimal places, and also has a rounding effect, but this is not perfect, If the number of decimal place of the parameter itself is equal to 2 is possible, such as 3.1415, but such as 3 or 3.0 is not a perfect implementation, continue to see below.
3.var xsd=value.tostring (). Split ("."), using the dot "." Value is separated into an array.
4.if (xsd.length==1) {value=value.tostring () + ". XX"; return value, if the length of the array is 1, that is, there is no decimal, then two 0 will be added to the number, for example 3 will be converted to 3.00.
5.

?
123456 if(xsd.length>1){ if(xsd[1].length<2){  value=value.toString()+"0"; } returnvalue; }

if (xsd.length>1) is used to determine whether the length of the number is greater than 1, that is, if the number has decimals, if there are decimals, but the number of decimal places is less than 2, which is similar to 3.1, it will add a 0, that is, will be converted to 3.10.

The second method: multiple ways to summarize the function of formatting data in JS to preserve two decimal places

The best way:

Keep two bits like that.

?
12 vara = 9.39393; alert(a.toFixed(2));

Description

Alert (number.tofixed (9.39393));
The return is 9.39.
However, only ie5.5 versions are supported.

Other methods:

Method One:

?
1234567891011121314 function roundFun(numberRound,roundDigit) //四舍五入,保留位数为roundDigit  { if (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; }   }

Method Two:

?
12345 <script>  tmp = "1234567.57232" result = tmp.substr(0,tmp.indexOf(".")+3);  alert(result);  </script>

Third method: JavaScript retains two-bit decimal code

?
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 <script type="text/javascript">   //保留两位小数   //功能:将浮点数四舍五入,取小数点后2位   function toDecimal(x) {    var f = parseFloat(x);    if (isNaN(f)) {     return;    }    f = Math.round(x*100)/100;    return f;   }     //制保留2位小数,如:2,会在2后面补上00.即2.00   function toDecimal2(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);    }   //四舍五入   alert("保留2位小数:" + toDecimal(3.14159267));   alert("强制保留2位小数:" + toDecimal2(3.14159267));   alert("保留2位小数:" + toDecimal(3.14559267));   alert("强制保留2位小数:" + toDecimal2(3.15159267));   alert("保留2位小数:" + fomatFloat(3.14559267, 2));   alert("保留1位小数:" + fomatFloat(3.15159267, 1));      //五舍六入   alert("保留2位小数:" + 1000.003.toFixed(2));   alert("保留1位小数:" + 1000.08.toFixed(1));   alert("保留1位小数:" + 1000.04.toFixed(1));   alert("保留1位小数:" + 1000.05.toFixed(1));      //科学计数   alert(3.1415.toExponential(2));   alert(3.1455.toExponential(2));   alert(3.1445.toExponential(2));   alert(3.1465.toExponential(2));   alert(3.1665.toExponential(1));   //精确到n位,不含n位   alert("精确到小数点第2位" + 3.1415.toPrecision(2));   alert("精确到小数点第3位" + 3.1465.toPrecision(3));   alert("精确到小数点第2位" + 3.1415.toPrecision(2));   alert("精确到小数点第2位" + 3.1455.toPrecision(2));   alert("精确到小数点第5位" + 3.141592679287.toPrecision(5));  </script>

The above is the JavaScript implementation of two decimal places to maintain a variety of methods, hope that everyone's learning to help.

JavaScript implements several methods to preserve two decimal places

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.