1

i choose this answer over the type="number" one becouse users can just press f12 and get rid of it

adding

type="number"

to my html works but that still doesn't explain why an - works without adding it to

for the minus is what i thought it works becouse - is not an string opperator and + is

I was testing with typescript and I noticed this so when I use minus it works when I use + it does work and I don't know how and can't find where I can find it

my class:

export class Add {
number1: Number;
number2: Number;
total: Number;
}

i have tried giving them into let this is my function

Math(): void {
let numberone = this.add.number1;
let numbertwo = this.add.number2;
this.add.total = numberone + numbertwo;
}

expected result where

numberone = 10
numbertwo = 10
this.add.total = numerone + numbertwo

that the total is becoming 20 but it becomes 1010

my html

<h2>here you can add stuff</h2> 
<div><span>first number: </span><input [(ngModel)]="add.number1" 
placeholder="number1"></div>
<div><span>second number: </span><input [(ngModel)]="add.number2" 
placeholder="number2"></div>
<button (click)="Math()">press here to add</button> <label>{{add.total}}</label>
Marc Roelse
  • 95
  • 1
  • 12
  • next to that i cant find it on google i find de error not very clear but that is something else – Marc Roelse Feb 13 '19 at 08:16
  • Please provide a [mcve] of your issue. –  Feb 13 '19 at 08:20
  • i have manetched to get visual studio code debug working with angular and it looks like there is something wrong with my input but why does - works and + doesn't even to i have said that they needed to be a number it makes them an string – Marc Roelse Feb 13 '19 at 08:35

3 Answers3

2

Following your comment on your question : your issue is that you get the numbers from inputs.

Inputs are always text :

function log(input) {
  console.log(input.value + ' is of type ' + typeof input.value);
}
<input type="text" placeholder="input something here" oninput="log(this)">
<br>
<input type="number" placeholder="input something here" oninput="log(this)">

To resolve that, you need to convert your input values into numbers.

Very easy : just append a + in front of it.

If you have

<input type="number" [(ngModel)]="number1">

Then you will do

add() {
  result = +this.number1 + +this.number2;
}

resulting in a correct addition :

console.log(+'10' + +'10');

EDIT: as shown in the other answers (but with the wrong explanations), Angular converts inputs of type="number" into numbers if your variables are typed as numbers.

You can then take advantage of it, and indeed, type your inputs and your variables as numbers. But it's always better to understand the basics, instead of using something without understanding it !

EDIT 2: To make subsctractions, follow the same logic

console.log(+'10' - +'10');
  • i will try that – Marc Roelse Feb 13 '19 at 08:47
  • this also works it is an interesting way of doing it and i learnt from it thanks – Marc Roelse Feb 13 '19 at 08:51
  • @MarcRoelse to better understand the concept, [here is a question on SOF](https://stackoverflow.com/questions/35791767/html-input-type-number-still-returning-a-string-when-accessed-from-javascript) that explains why it behaves likes that. –  Feb 13 '19 at 08:58
  • i excepted this answer before the type="number" becouse this could be used in javascript and type script and is more safer to use why you can just get rid of the type="number" becouse it is an html element but i still dont know why the - doesn work without doing any of this – Marc Roelse Feb 13 '19 at 09:03
  • @MarcRoelse in JS, you can concatenate strings with "+", but you can't subtract them. `'x' + 'y' === x.concat(y)` is true in JS. When you use a minus, the JS engine says "Well I can't substract strings ! maybe it would work if I converted them into numbers ?", and so it does. You can try it with strings too : `'x' - 'y' === NaN` will output true : the engine tried to convert the strings into numbers, but it couldn't, so it considers it as a NaN (Not A Number) –  Feb 13 '19 at 09:07
  • thanks for this nice explaination @trichetriche thanks and now i could use that to make an try parse if i want to – Marc Roelse Feb 13 '19 at 09:14
  • when i was making an subtract version of this code i used your + in front of the vars and it add stuff for some reason but it is an easy fix just get rid of the + in front of it but is there also an explanation for this or is that just js – Marc Roelse Feb 13 '19 at 09:39
  • @MarcRoelse I've made an edit #2, feel free to check it –  Feb 13 '19 at 10:22
1

You should use number, not Number

Number is not a type, it's an interface of es5. Here's its definition

interface Number {
    /**
      * Returns a string representation of an object.
      * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers.
      */
    toString(radix?: number): string;

    /**
      * Returns a string representing a number in fixed-point notation.
      * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.
      */
    toFixed(fractionDigits?: number): string;

    /**
      * Returns a string containing a number represented in exponential notation.
      * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.
      */
    toExponential(fractionDigits?: number): string;

    /**
      * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.
      * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive.
      */
    toPrecision(precision?: number): string;

    /** Returns the primitive value of the specified object. */
    valueOf(): number;
}

You also miss the type="number" in the input, so it convert your value to string

Your html should be

<h2>here you can add stuff</h2> 
<div><span>first number: </span><input [(ngModel)]="add.number1" 
placeholder="number1" type="number"></div>
<div><span>second number: </span><input [(ngModel)]="add.number2" 
placeholder="number2" type="number"></div>
<button (click)="Math()">press here to add</button> <label>{{add.total}}</label>
<button (click)="goBack()">go back</button>

About the reason the - work but the + doesn't, it is because string type doesn't have the "-" operator. Therefore, it converts the strings to the numbers. It doesn't happen on "+"

Nguyen Phong Thien
  • 3,237
  • 1
  • 15
  • 36
  • This won't solve the issue, because it is just a typing. If he writes `add.number1 = 10`, it will consider number1 as a number. –  Feb 13 '19 at 08:22
  • No, if the type is predefined as ```Number```, it will still be ```Number```. If it is not predefined, it will be assigned as ```number``` – Nguyen Phong Thien Feb 13 '19 at 08:26
  • You can try ```number1: Number = 10;```, then ```number1``` will be ```Number```, not ```number``` – Nguyen Phong Thien Feb 13 '19 at 08:27
  • JS have dynamic typing, meaning the typing depends on the assignation. numbers being numbers and not objects, if you assign a number to a variable, it becomes a number. –  Feb 13 '19 at 08:29
  • i already tried using number it does get rid of the error but doesn't fix the error and as said by @trichetriche it would make it automitc an number But thanks for the explanation of Number – Marc Roelse Feb 13 '19 at 08:31
  • typeof is not a type check function, especially if it is a Interface, not a type. You can hover the mouse over the x at the line x = 10, you'll see the type of x – Nguyen Phong Thien Feb 13 '19 at 08:33
  • Typescript types are not javascript types. I'm telling you your answer won't solve the issue, that's all. No need to argue about something entirely different. –  Feb 13 '19 at 08:40
  • @MarcRoelse you need to add type="number" to the input, otherwise it'll convert the value to string – Nguyen Phong Thien Feb 13 '19 at 08:40
  • @trichetriche I tested my answer, it works, of course after adding type="number" to the input. That is a different issue – Nguyen Phong Thien Feb 13 '19 at 08:41
  • it works but that doesnt explain why - does work without adding type="number" if somebody has an eplaination for that i would like to know – Marc Roelse Feb 13 '19 at 08:46
  • @MarcRoelse input has default ```type="text"``` Therefore it make the value ```string```, not ```number``` by default. Typescript only help you to verify type in development and build time, not run time. therefore it doens't help you to transform a value from a string to a number. – Nguyen Phong Thien Feb 13 '19 at 08:50
  • @NguyenPhongThien ok, this one is on me, I didn't understand that from your comments. In this case, it works **because of Angular**, not because of the type number on the input. –  Feb 13 '19 at 08:52
  • @NguyenPhongThien that explained what input does i am not very experienced with angular stuff yet but it doesn't explain why an - does work from direct input and an + doesn't is it becouse - can only do - thing so it automaticly converts it to an number – Marc Roelse Feb 13 '19 at 08:53
  • you can remove the type number from the input and try, I tried all the cases before commenting. – Nguyen Phong Thien Feb 13 '19 at 08:53
  • @MarcRoelse a - doesn't exist in ```string``` operator, so it converts the data to number. But + does, so it keep the type – Nguyen Phong Thien Feb 13 '19 at 08:55
  • 1
    yeah i thought that @NguyenPhongThien and it was best way to explain it in my head and i will choose the answer from trichetriche over yours why html elements are never an good idee to fix a backend problem becouse user can use f12 to get rid of it but now i do know that angular makes it an number that is nice thanks for that – Marc Roelse Feb 13 '19 at 09:11
0

In Add class use type number (first letter lower-case)

Update (question)

In <input> use type="number"

Working example here

Explanation:

First problem - when you use Number instead of number then you get compilation error. After fix it, you face another problem - input value was interpreted by js/angular like string(and '10'+'10' give string concatenation - but if you type '10'-'10' then js implict cast strings to numbers and make substraction) - but when you use type="number" then input values was implicit cast to numbers by js/angular - and you get right result.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • This won't solve the issue, because it is just a typing. If he writes `add.number1 = 10`, it will consider number1 as a number. –  Feb 13 '19 at 08:22
  • @trichetriche OP in his question never set `add.number1 = 10` - he do something opposite: `let numberone = this.add.number1;`. So fixing the type in `Add` class in his case solve the issue – Kamil Kiełczewski Feb 13 '19 at 08:44
  • Okay, then provide a [mcve] showing that it works. I'm waiting. By the way, `type="number"` still creates strings. –  Feb 13 '19 at 08:46
  • type="number " is not creating string for me but i think it is something by angular – Marc Roelse Feb 13 '19 at 08:57
  • Again, as explained on the other answer, `type="number"` do create strings. In Angular, they are considered as numbers **because of Angular**, that converts strings into numbers when the input is of type number. You can easily test this is any JS sandbox, or just look at my answer to see it in action. So, it working in an Angular context isn't the truth, this is the framework doing. –  Feb 13 '19 at 09:01
  • i explained why i choose trichetriche answer over type="number" in de top of my question for people that run in the same problem or have the same question – Marc Roelse Feb 13 '19 at 09:17