Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

How to convert string to number with AngularJS

There is more than one way to convert string to number in JavaScript.

Context:

  • Use AngularJS to bind text boxes to variables.
  • Sum up input values in some text boxes.
  • Omit ng-required, ng-pattern, ng-minlength, ng-maxlength, etc., wherever possible.
  • Use {{~}} to print summed up value.
  • Should handle values larget than 32-bit integer.
  • String “45a”, “0xAB”, “-0xDE”, “2e4”, and “Inifinity” should be treated as illegal value (NaN) or 0.

Comparison:

There is no only neat things to do …

  • parseInt(value, 10) … Convert “45a” to 45, “0xAB” to 171, “-0xDE” to -222, and “2e4” to 2. Could not be used in AngularJS {{ ~ }} because it create a new object.
  • parseFloat(value) … Convert “45a” to 45, “2e4” to 20000, and “Infinity” to Infinity. Could not be used in AngularJS {{ ~ }} because it create a new object.
  • Number(value) … Convert “0xAB” to 171, and “Infinity” to Infinity. Could not be used in AngularJS {{ ~ }} because it create a new object.
  • value|0, value>>0, value<<0, … Convert “0xAB” to 171, and “2e4” to 20000. Cannot handle value larger than 231 (=2147483648).
  • +value … Convert “0xAB” to 171, “2e4” to 20000, and “Infinity” to Infinity. {{ (+a) + (+b) | number }} is treated as string concat on AngularJS 1.2.1 (no problem on AngularJS 1.4.8)
  • value*1 … Convert “0xAB” to 171, “2e4” to 20000, and “Infinity” to Infinity. {{ undefined*1 }} becomes NaN on AngularJS 1.4.8 (no problem on JavaScript console…)
  • value-0 … Convert “0xAB” to 171, “2e4” to 20000, and “Infinity” to Infinity.

Comparison of these code on some values: http://jsfiddle.net/satob/fu1sjtmd/

To treat “0xAB”, “-0xDE”, “2e4”, and “Inifinity” as illiegal value, you should use ng-pattern to cutoff non-digit characters like this: http://jsfiddle.net/satob/8oeLfLrz/