skip to Main Content

I hope I am explaining this correctly and apologize for any misunderstandings.

I would like to change some 2 decimal places numbers as below:

18.40 should become-> 18.40
18.41 should become-> 18.41
18.42 should become-> 18.42
18.43 should become-> 18.43
18.44 should become-> 18.44
18.45 should become-> 18.5
18.46 should become-> 18.5
18.46 should become-> 18.5
18.46 should become-> 18.5
18.46 should become-> 18.5

Basically i want to change the numbers based on the last digit in the number. If the last digit ( 2nd digit in 2 decimal places number) is 5 or greater than the first digit in 2 decimal place number should change to next incremental number.

For example 18.46 . 6 is greater than 5 so the 4 before the 6 should become 5. So the number will be 18.5

I hope this is clear now.

Thanks.
Basically

3

Answers


  1. You can use a built-in toFixed method of Number class for this case.

    Login or Signup to reply.
  2. You can strip off the decimal portion, round that, then add that back to the integer portion:

    const values = [18.40, 18.42, 18.45, 18.48]
    const formatted = values.map(roundIt)
                                 
    function roundIt(v){
      let int = v|0
      let dec = v - int
      dec = Math.round( Number.parseFloat(dec).toFixed(2) * 10 ) / 10
      return Number.parseFloat(dec < .5 ? v : int+dec).toFixed(2)
    }
    
    console.log(formatted)
    Login or Signup to reply.
  3. You could convert it by looking to the last digit.

    const
        convert = v => (v * 100).toFixed(0) % 10 < 5 ? v : v.toFixed(1),
        data = [[18.40, 18.40], [18.42, 18.42], [18.45, 18.5], [18.48, 18.5]];
    
    data.map(([v, w]) => console.log(v, convert(v), w));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search