简体   繁体   中英

How to round up or round down decimal places?

Let's say I want to suggest a bid for users in a reverse of forward manners.

For reverse:

  • 1.23 => 1.20
  • 2.35 => 2.30
  • 3.59 => 3.50
  • 4.99 => 4.90

For forward:

  • 1.23 => 1.30
  • 2.35 => 2.40
  • 3.59 => 3.60
  • 4.99 => 5.00

I've tried using math.floor() and math.ceil() , but it will only round it off to the nearest integer. Can you give me a solution or suggestion for this?

You can use Math.floor(a*10)/10 and Math.ceil(a*10)/10 where a is the number you want to round.

 console.log(Math.floor(1.23*10)/10) console.log(Math.floor(2.35*10)/10) console.log(Math.floor(3.59*10)/10) console.log(Math.floor(4.99*10)/10) console.log('') console.log(Math.ceil(1.23*10)/10) console.log(Math.ceil(2.35*10)/10) console.log(Math.ceil(3.59*10)/10) console.log(Math.ceil(4.99*10)/10) 

If you need the final value as a string in the format X.YY (and not XY) you can use toFixed(2) (ie (Math.ceil(1.23*10)/10)).toFixed(2) )

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