I have some data like RM 28.51 (Currency), RM30.28(Currency) in my table and need to use these data to do some calculation
my solution is to parseFloat(28.51).tofixed(2) + parseFloat(30.28).tofixed(2)
but when the moment more and more data come in , sometimes they will some decimal point error shown as result
Example my result at the end will show 3859.39 but the actual is 3859.40
Is there any better solution?
parseFloat(28.51).toFixed(2) + parseFloat(30.28).toFixed(2)- sometimes they will some decimal point error shown as result
The JavaScript toFixed method takes in a number and outputs a string
When you use + with two numbers, you add both numbers.
When you use + with two strings, you join both strings together.
The example below illustrates the difference.
function addTwoStrings(value1, value2) {
return parseFloat(value1).toFixed(2) + parseFloat(value2).toFixed(2)
}
function addTwoNumbers(value1, value2) {
return (parseFloat(value1) + parseFloat(value2)).toFixed(2)
}
console.log(addTwoStrings(28.514, 30.284))
console.log(addTwoNumbers(28.514, 30.284))