Pedro
Pedro

Reputation: 1477

comparing decimal numbers in javascript

im having issues comparing km distance, it saying in the example above, im comparing distance between locations, these locations are in km.

9,441.4<1500

The output is telling me that 9 thousand is less than 1 thousand. In my case, should i only put or add in 1500 the dot and comma to be 1,500.0, or there is more than just that?

Upvotes: 2

Views: 115

Answers (2)

stdob--
stdob--

Reputation: 29172

As T.J. Crowder said, you need to remove the comma, and convert the string to a floating point number:

$api_input = "9,441.4";

$tmp = str_replace( ",", "", $api_input);

$distance = floatval($tmp);

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074038

You should remove the comma. You don't use a thousands separator in JavaScript numbers.

So why didn't it fail with a syntax error? Because it's valid syntax: JavaScript has a comma operator. Your code was the number 9, followed by the comma operator, followed by the comparison 441.4 < 1500. The comma operator is one of JavaScript's more...interesting...operators: It evaluates the left-hand operand (9 in your example), throws away the resulting value, then evaluates its right-hand operand (441.4<1500 in your example) and takes the resulting value as the value of the comma operator expression.

You wanted:

9441.4<1500

Upvotes: 5

Related Questions