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
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
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