skip to Main Content

For example I have the following numbers:

30, 270, 530, 1110

but I want each to round up to:

40, 280, 540, 1120

Is that possible?

2

Answers


  1. Just divide by 20, round and multiply by 20:

    const nums = [30, 273, 530, 1110];
    
    nums.forEach(num => {
      const rounded = Math.round(num / 20) * 20;
      console.log(rounded);
    });
    Login or Signup to reply.
  2. I think that the previous solution is wrong because 530 should be round to 520 instead of 540 because:

    540 / 40 = 13.5

    40 * 13 = 520

    40 * 14 = 560

    My code is longer but meet the previous requirements:

    const array = [30, 270, 530, 1110]
    
    const arrayMod = array.map(e => e / 40) //  [0.75, 6.75, 13.25, 27.75]
    
    const arrayModDInt = arrayMod.map(e => parseInt(e)) //  [0, 6, 13, 27]
    
    const arrayModDDecimal = arrayMod.map(e => e % 1) // [0.75, 0.75, 0.25, 0.75]
    
    const arrayRound = arrayModDDecimal.map(e => e >= 0.5? 1 : 0) // [1, 1, 0, 1]
    
    const finalArrayResult = []
    
    for(var i=0;i<arrayModDInt.length;i++){
        finalArrayResult[i] = (arrayModDInt[i] + arrayRound[i]) * 40
    }
    
    console.log(finalArrayResult) // [40, 280, 520, 1120]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search