Reputation: 567
I have a condition that will check if a number is greater than 50,000, if so we show an alert. This works fine, but if you input this 50,000.99 it doesn't trigger the alert, but 51,000.00 does. How do I use a conditional correctly here?
here is my code:
if (parseInt(newValue) > 50000.00) {
toastr.info('Number can not be more than $50000.00');
// do something
} else {
// do something
}
Upvotes: 2
Views: 11019
Reputation:
Use parseFloat instead of parseInt when working with decimal values.
parseInt("234")//234
parseInt("234.551")//234
parseInt(".234")//NaN
parseFloat("234")//234
parseFloat("234.551")//234.551
parseFloat(".234")//0.234
+("234")//234
+("234.551")//234.551
+(".234")//0.234
Upvotes: 1
Reputation: 288510
Don't use parseInt
to parse decimal numbers:
Instead, you could use parseFloat
. But wait:
There is a better approach: the unary +
operator:
But wait: when you use the greater-than Operator >
, the operands are automatically converted to numbers (unless both are strings).
So just use
newValue > 50000
Upvotes: 6
Reputation: 781779
Use parseFloat
, not parseInt
, if you want a number with a fraction. Integers don't have fractions. Real numbers have fractions, and they're represented in computer programs as floating point.
Upvotes: 1
Reputation:
Use parseFloat:
if (parseFloat(newValue) > 50000.00) {
toastr.info('Number can not be more than $50000.00');
// do something
} else {
// do something
}
The parseFloat() function parses a string argument and returns a floating point number.
Upvotes: 1
Reputation: 4309
Don't use parsint. It converts your string/number to an integer, effectively lopping off the decimal.
Upvotes: 2