Home >Web Front-end >JS Tutorial >Implement js code to retain N digits after the decimal point_javascript skills
In JS, if you want to retain N digits after the decimal point, you usually use the toFixed function
The rounding conversion function is as follows:
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
The above is all the code. Isn’t it super simple? I hope it can be helpful to everyone