Numbers comparison in typescript

Viewed 18665

My question might be silly, and I actually have a workaround to solve this issue. But I'm still interested in why it happens. I have two numbers in my typescript file. Here is their definition.

mAlarmValue:number;
levelValue:number;

In my HTML input box which I also set the attribute type="number", I filled a number for mAlarmValue. After that, I did a comparison between those two numbers. Here is what I did.

console.log('Value =',this.mAlarmValue);
console.log("levelValue=",this.levelValue);
if (this.mAlarmValue <= this.levelValue) {
  console.log("true");
}

And this is the actual console output.

Value = 10
levelValue= 5
true

Apprently 10 is greater than 5, but the result showed otherwise. My workaround is to convert the number to string and then convert it back to number.

console.log('Value =',this.mAlarmValue);
console.log("levelValue=",this.levelValue);
if (parseFloat(this.mAlarmValue.toString()) <= this.levelValue) {
  console.log("true");
} else {
  console.log(false)
}

Now it shows the correct result.

Value = 10
levelValue= 5
false

Does anyone have idea what's going on here? Thanks for your time.

2 Answers

The type of the value property of an HTMLInputElement is always string, even if you set type="number". I'm guessing that somewhere in your code you have something like this:

this.mAlarmValue = $('#Alarm').val() as number;

Although this will compile, since the values are really strings, you will get the wrong result at runtime (for example, "10" < "5" is true). To fix this, you need to use parseFloat at the moment you read from the <input> element, such as

this.mAlarmValue = parseFloat($('#Alarm').val() as string);

Or, in case you're using Vue.js, make sure that you use v-model.number="mAlarmValue" to correctly convert string values to numbers.

My workaround is to convert the number to string and then convert it back to number.

You can do something like below in latest es6

  • converting string to number => this.mAlarmValue = +this.mAlarmValue
  • converting number to string => this.mAlarmValue = " " + this.mAlarmValue

Then you can do something like below for your case

    if (+mAlarmValue >= +levelValue) {
         console.log(true);
    } else {
         console.log(false);
    }

for more information about converting the types in Typescript check here

TypeScript Converting a String to a number

Related