Home >Web Front-end >JS Tutorial >Implement js code to retain N digits after the decimal point_javascript skills

Implement js code to retain N digits after the decimal point_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:31:231281browse

In JS, if you want to retain N digits after the decimal point, you usually use the toFixed function

Copy code The code is as follows:


The rounding conversion function is as follows:

Copy code The code is as follows:

function round(v,e){
var t=1;
for(;e>0;t*=10,e--);
for(;e<0;t/=10,e );
return Math.round(v*t)/t;
}

In parameters:

v represents the value to be converted

e represents the number of digits to be retained

The two fors in the function, this is the key point,

The first for is for the situation to the right of the decimal point, that is, how many digits to the right of the decimal point are retained;

The second for is for the situation to the left of the decimal point, that is, how many digits to the left of the decimal point are retained.

The function of for is to calculate the value of t, that is, the multiple of how much v should be enlarged or reduced (multiple = t).

For here takes advantage of two features in for, conditional judgment and counter accumulation (loop),

For continues when e satisfies the condition, and each time e is accumulated (each accumulation of e is to create a condition for for that does not satisfy the loop), the value of t is also calculated.

Finally, the native round method is used to calculate the result of the enlarged/reduced v, and then the result is enlarged/reduced to the correct multiple

The following examples of reserved two-digit numbers

Copy code The code is as follows:


The above is all the code. Isn’t it super simple? I hope it can be helpful to everyone

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn