search

Home  >  Q&A  >  body text

javascript - problem of preserving decimals in integers

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?

世界只因有你世界只因有你2744 days ago567

reply all(5)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:14:54

    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?

    reply
    0
  • 某草草

    某草草2017-05-19 10:14:54

    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.

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:14:54

    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

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:14:54

    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

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:14:54

    parseFloat(1.236.toFixed(2))

    reply
    0
  • Cancelreply