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
CodePudding user response:
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)
CodePudding user response:
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));
CodePudding user response:
You can use a built-in toFixed method of Number
class for this case.