javascript - problem of preserving decimals in integers
世界只因有你
世界只因有你 2017-05-19 10:12:54
0
5
583

I hope to keep a number to two decimal places. If there are decimal places, round them off. If not, fill in 0.
For example,
1=》1.00
1.234=》1.23
1.256=》1.26

I tried using the toFixed function, and its content is correct, but it returns a string. For example, 1.00 is a string. When I explicitly convert Number(1.00), it becomes 1.

So how do I get the number to retain two decimal places and the return type is a number?

世界只因有你
世界只因有你

reply all(5)
淡淡烟草味

My guess is: If it is used for page display, then strings don’t matter, right? If it is used for operation, it doesn't matter even if it is 1 (not 1.00), right?

某草草

1.00 This format can only be saved as a string, and cannot be saved as a numeric type.

No matter what you do, if you want to display something like 1.00, you can only use strings.

左手右手慢动作

First of all, the toFixed method itself is buggy. Secondly, the Number structure in js does not contain precision. If you need numbers that contain precision, you can just write a class yourself

仅有的幸福
var num=1.256;
Math.floor(Math.round(num*100))/100;

可以封装成方法:
function unitNormalization(arr,digit){
        /*单位规整*/
        var digit=digit||0;
        var prence=Math.pow(10,digit);
        if(Array.isArray(arr)){
            var backArr=[];
            for(var i=0;i<arr.length;i++){
                backArr.push(Math.rou(Math.round(arr[i]*prence))/prence);
            }
            return backArr;
        }else{
            var num=Math.floor(Math.round(arr*prence))/prence;
            return num
        }
    }

unitNormalization(1.253,2)//1.25
unitNormalization(1.257,2)//1.26
我想大声告诉你

parseFloat(1.236.toFixed(2))

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template