简体   繁体   中英

How to show one decimal place (Without rounding) and show .0 for whole numbers?

Is there a nice way to show show decimal numbers with one decimal place all the time but without rounding? So you have the following numbers:

3.55
3.5
3

and I want them to show

3.5
3.5
3.0

you can also use the toFixed() method, though this converts the float to a string.

var float = 3.55

float.toFixed(1);

This will round but rounds down a decimal of 0.5 in any position

Use Math.floor instead.

pad(Math.floor(num * 10) / 10);

where pad adds .0 if it needs to.

Keep in mind that Math.round is probably better. Since 3.55 should be 3.6 .

Try this (where x is your float):

function format_float(float x )
 {
   if ((x).tostring().contains(".") ) 
   {return parseFloat((x).tostring().Substring(0,indexof(".")+1)) ;}
   else 
   {return x.toFixed(1);}
 }

To remove the need for a pad function:

function toOnePlace(n) {
  n = ('' + n).split('.');
  return n[0] + '.' + (n[1]? n[1].charAt(0) : 0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM