-1

I want my number to have max length of 4 digits. For example:

input 1.234567 should output 1.236
input 12.34567 should output 12.34
input 123.4567 should output 123.5
Lukas
  • 37
  • 6
  • What is your question? What do you mean by "should output"? – Scott Hunter Jun 14 '22 at 20:01
  • What about 123456 or 0.000000123456? – Barmar Jun 14 '22 at 20:02
  • I don't see any rhyme or reason for the output you expect – j08691 Jun 14 '22 at 20:02
  • Why is the first one `1.236`? Shouldn't it be `1.234` or `1.235` (depending on whether you want to round down or nearest)? – Barmar Jun 14 '22 at 20:03
  • Figure out how many digits there are before the `.`. Subtract that from the max nunber of digits, then use that as the number of decimal places in `toFixed()`. – Barmar Jun 14 '22 at 20:04
  • 1
    `var number = 1.234567;` `console.log(number.toFixed(3));` Is not going to be 1.236 tho, the closest rounded number will be 1.235 – Chris G Jun 14 '22 at 20:04
  • Does this answer your question? [How can I round to an arbitrary number of significant digits with JavaScript?](https://stackoverflow.com/questions/36369239/how-can-i-round-to-an-arbitrary-number-of-significant-digits-with-javascript) – isherwood Jun 14 '22 at 20:14
  • Lukas, please take the [tour]. You haven't resolved any of your earlier posts, and you shouldn't have reposted this one. You should improve it. – isherwood Jun 15 '22 at 14:02

1 Answers1

1

You need to decide whether you want to round that last number or not. It was rounded incorrectly in the first example, rounded up in the second, and not rounded in the third.

Anyways, here is a function that rounds the 4th digit up. Also, you can change the amount of digits if you like by changing the 'count' property. I realize it's long, probably a more efficient way.

function fourNums(num, count) {
let number = []
let digits = count
num.toString().split('').forEach(char => {
    if (digits === 1) {
        if (char === '.') {
            number.push(char)
        } else {
            number.push(( parseInt(char) + 1).toString())
            digits -= 1
        }
    } else if (digits > 0) {
        if (char === '.') {
            number.push(char)
        } else {
            number.push(char)
            digits -= 1
        }
    }
})
return number

}

fourNums(1.234567, 4) // 1.235

fourNums(12.34567, 4) // 12.35

fourNums(123.4567, 4) // 123.5