0

I have some floating point number that i am obtaining. The number has strictly two decimal places and shall never be more than that.

I want to test if the number i have is a float and then make this two decisions.

  1. If the number is equal to 5 but never greater than 5

  2. If number is equal to 20 but never greater than 20 but never lesser than 5

I have this code

var get_sum = 4.45;

var dist = parseFloat(get_sum);

if(typeof(dist) == 'number' && dist == 5 || dist < 5){
          }
if(typeof(dist) == 'number' && dist == 20 || dist < 20 && dist > 5){
          }

Since i am dealing with floats me thinks == is a bad idea and i might get the wrong results.

Will my code always guarantee me correct results?.

Gandalf
  • 1
  • 29
  • 94
  • 165
  • `parseFloat` doesn't do anything if you already have a `number`, I believe – CertainPerformance Jan 12 '19 at 11:57
  • well, there is no other way i can check if its a float(without using es6) since technically its a double. – Gandalf Jan 12 '19 at 11:58
  • Javascript isn't Java, there's not really any such thing as integer vs double, everything numeric is just a `number` – CertainPerformance Jan 12 '19 at 12:00
  • Why do you check the type of `dist`? `parseFloat()` would only return `NaN` if `get_sum` cannot be parsed as a number but it is already a number - or is it a string? – Andreas Jan 12 '19 at 12:03
  • Possible duplicate of [Avoiding problems with JavaScript's weird decimal calculations](https://stackoverflow.com/questions/5037839/avoiding-problems-with-javascripts-weird-decimal-calculations) – Andreas Jan 12 '19 at 12:07
  • I am obtaining it from local storage so some malicious user might change it to string and wreck the program. – Gandalf Jan 12 '19 at 12:18
  • They could also just change the program. – Dave Newton Jan 12 '19 at 20:35

1 Answers1

1

From W3C:

JavaScript Numbers are Always 64-bit Floating Point

So you can't really test if the number i have is a float, because every instance of a number in JavaScript is of the same type (the type number, related to the object Number).

NB: parseFloat always returns a number, if it can't parse the float, it returns NaN (which is still a number), so your typeof(dist) == 'number' is useless ;)

Nino Filiu
  • 16,660
  • 11
  • 54
  • 84