Jquery - toFixed, but not toFixed

Using toFixed as below:

var a=0.5, b=1, c=1.5;
console.log(a.toFixed(), b.toFixed(), c.toFixed());
// 0.5 1.0 1.5

However, when it is an integer, I want it to return "1".

Help!

+3
source share
3 answers

You can use a regex to remove the trailing .0if one exists:

Number.prototype.safe_toFixed = function (x) {
    var that = this.toFixed(x);
    return that.replace(/\.0$/, '');
}
+2
source

This is what I did, and it works every time.

var x= Number(54.03).toFixed(1);

  if(Math.floor(x) == x) {
     x = Math.floor(x);
  }

alert( x );

I just compare these two types to see if they match. If they do, I know what may or may not be an extra zero. Anyway, I just round (ceil) or down (floor) and get an integer without annoying decimal and trailing zero.

+1
source

You can use the condition split()and if:

    var digit = 1.2
    var ret = digit.toFixed(1);
    var intValue = ret.split('.');
    if(intValue[1] == 0){
      digit = intValue[0];
    }
0
source

Source: https://habr.com/ru/post/1788413/


All Articles