简体   繁体   中英

how to get customised ceil and floor value for a given variable?

I want customized ceil and floor using javascript. Here for ex: if the particular floating point variable 10.1 then I need the result as 10 (floor) if the value is more than 10.1 then I need to make it 11 (ceil). here 10 would be variable. Can anyone give me a solution?

Better to do it with Math instead of adding a decimal. Subtract the whole number, check the remainder, update the whole number if greater than .1 and return it.

 function customRound (num) { let wn = Math.floor(num) let adj = num - wn > .1 ? 1 : 0 return wn + adj } console.log('10.1', customRound(10.1)) console.log('10.11', customRound(10.11)) console.log('10.01', customRound(10.1)) console.log('10.100000000001', customRound(10.100000000001)) 

Here's one way:

Math.round(thing + 0.4);

Say thing = 2.11, then you're rounding 2.51 = 3. If thing = 2.09, you round 2.49 = 2. Should work!

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