0

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.

Oliver
  • 35
  • 1
  • 7

2 Answers2

2

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.

Mu-Tsun Tsai
  • 1,883
  • 1
  • 7
  • 22
0

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

ganesh045
  • 4,099
  • 2
  • 11
  • 32
  • This is a very clever and concise way to do type conversion. I'll probably use it in my personal projects only as it seems to lose a bit readability to me. – Oliver Jul 04 '19 at 07:53
  • Yeah, but I never mind using latest ECMAScript features.. :) – ganesh045 Jul 04 '19 at 09:23