This chapter introduces how to achieve the effect of retaining two decimal places for numbers. If the original decimal places of a number are less than two, then the missing ones will be automatically filled with zeros. This is also for the purpose of uniformity. Let’s look at the code example first:
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 achieves our requirements. Here is an introduction to its implementation process.
1. Code comments:
1.function returnFloat(value){}, the parameter is the number to be converted.
2.var value=Math.round(parseFloat(value)*100)/100, this should be the core of the function, parseFloat(value) converts the parameter into a floating point number, because the parameter may be a string, The reason for multiplying by 100 is to retain two decimal places. First move the decimal point two digits to the right, then use the Math.round() method to perform rounding calculations, and finally divide by 100. In this way, two decimal places are retained. It also has a rounding effect, but this is not perfect. If the number of decimal places in the parameter number itself is greater than or equal to 2, it is ok, such as 3.1415, but there is still no perfect implementation such as 3 or 3.0. Continue to see below.
3.var xsd=value.toString().split("."), use dot "." value to separate it into an array.
4.if(xsd.length==1){value=value.toString()+".00";return value;}, if the length of the array is 1, that is to say, there is no decimal, then it will Add two zeros to the number, for example 3 will be converted to 3.00.
5.
if(xsd.length>1){ if(xsd[1].length<2){ value=value.toString()+"0"; } return value; }
if(xsd.length>1) is used to determine whether the length of the number is greater than 1, that is, whether the number has a decimal. If there is a decimal, but the number of decimal digits is less than 2, which is similar to 3.1, it will be in Adding a 0 after it will convert it to 3.10.
2. Related learning tutorials:
1.Math.round() can be found in the chapter Javascript’s Math.round() method .
2. The parseFloat() function can be found in the javascript parseFloat() method chapter.
3. For the toString() function, please refer to the chapter The toString() method of the Number object in JavaScript .
4. The split() function can be found in the chapter The split() method of JavaScript’s String object.