jmccommas
jmccommas

Reputation: 567

greater than condition with number and decimal

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

Answers (5)

user2575725
user2575725

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

Oriol
Oriol

Reputation: 288510

Don't use parseInt to parse decimal numbers:

  • :( It truncates your numbers
  • :( It's unreliable unless you specify a radix
  • :( It's slow
  • :( It parses non numeric strings if they begin with a number

Instead, you could use parseFloat. But wait:

  • :) It does not truncate your numbers
  • :) There is no radix problem
  • :( It's slow
  • :( It parses non numeric strings if they begin with a number

There is a better approach: the unary + operator:

  • :) It does not truncate your numbers
  • :) There is no radix problem
  • :) It's so fast
  • :) It does not parse non completely numeric strings

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

Barmar
Barmar

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

user3998237
user3998237

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

CargoMeister
CargoMeister

Reputation: 4309

Don't use parsint. It converts your string/number to an integer, effectively lopping off the decimal.

Upvotes: 2

Related Questions