开发者

Round just decimal in Javascript

I have a value like that:

开发者_如何学Go

20.93

I'd like to round it to

20.90

How can I do that in Javascript ?

Thanks!


Multiply the number by 10, round it and then divide the number by 10:

var result = Math.round(20.93 * 10) / 10


I think this should work:

number.toFixed(1);


var num= 20.93
num = Math.floor(num * 10) / 10; // 20.9
num = Math.ceil(num * 10) / 10;  //21


I take it that you want the trailing zero. None of the answers give you that. It has to be a String to have the trailing zero.

function my_round(x){
  return Number(x).toFixed(1) + '0';
}

If you don't care about the trailing zero and you want a Number (not String), then here's another way to round to decimal places in JavaScript. This rounds to decimal place d.

function my_round(x, d){
  return Number( Number(x).toFixed(d) );
}

You would do

my_round('20.93', 1);

or

my_round(20.93, 1);


You can set toFixed(1). but set value = 20.96 then you have 21 and not 20.90;

BUT with my function always will be 20.90 than 20.93 like 20.98/97/96/95...

<script>

    var num = 20.93;

function vround(num) { // CREATE BY ROGERIO DE MORAES

    var Dif = (num.toFixed(2)-num.toFixed(1)).toFixed(2); 
    Dif = Dif * 100; 
    if(Dif <= -1) {

    var n = num.toFixed(2) - 0.05;
    vround(n);
     } else {
     var n = num.toFixed(1)+0;
    console.log(n);
     }
}

vround(num);

</script>

I create this function for get you value, but can change, if you wanna more forms.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜