vue.js retains two decimal places, rounds, rounds

vue.js retains two decimal places, rounds, rounds


This article is suitable for learning js and don't know how to keep the two friends after the decimal point to read ~

Four ways to keep two decimal places

The first:

var num =22.125456;//声明一个变量
num = num.toFixed(2); //num是上面的变量,toFixed是保留小数的意思
//括号里的数字是保留几位的意思,咱们写的是2,它就保留2位。
//这个方法是会四舍五入的,咱们这里写出来的输出结果是 22.13

The second kind:

function getnum()
{
var num = 22.123456;//声明变量
var figure = num.substring(0,num.indexOf(".")+3);

alert(figure );//在页面中弹出figure ,小伙伴们可以去试一下哦~
}

The parsing of this line of code is this:
declare a variable, of course, you can take other names, num after the equal sign is the above variable, substring is the meaning of intercepting the number in the string. Here is the interception of the number in 22.123456. It is about to start intercepting. The 0 in parentheses is a subscript, that is, the num after 0 is the content in the specified num, indexOf is the symbol in num, and the indexOf is in the brackets. Decimal point, and then +3, which means that the decimal point here is the second digit (because it is calculated by subscript), and the following +3 is the subscript of the decimal point to +3, which is equal to 5, and the result is 22.12.

The third kind:

function getnum()
{
var num=22.123456;
alert( Math.round(num*100)/100);
}

This is related to the round method in the meth object. This method is a bit special. It is rounded up. For example, 3.5 will be rounded to 4, and -3.5 will be rounded to -3. The format is the above format, you can try it in your own editor, you will understand more deeply!

Fourth:
regular expression

function getnum()
{
var num = 22.123456;
var aNew;
var re = /[0-9]+\.[0-9]{2}/;
aNew = num.replace(re,"$1");
alert(aNew);
}

Decimal adjustment

parseInt

parseInt()//括号里面写数字

rounding

Math.round();

Math.round(23.33333); // 23
Published 5 original articles · Likes0 · Visits200

Guess you like

Origin blog.csdn.net/Dream_Fever/article/details/103580552