How convert string to number in template

18,991 views
Skip to first unread message

Ladislav Prskavec

unread,
Sep 27, 2011, 7:07:51 AM9/27/11
to AngularJS
I have example: http://jsfiddle.net/abtris/rNTzz/3/

Result is 33,311

But i need 333 + 11 = 344

Is possible make in template?

Thx for help

Ladislav

Mårten Dolk

unread,
Sep 27, 2011, 7:46:20 AM9/27/11
to ang...@googlegroups.com
You are concatenating strings so this is expected. Either drop the '
(or use parseInt)

function Ctrl($resource){
this.items= parseInt('333');
this.next= 11;
}

2011/9/27 Ladislav Prskavec <ladislav...@gmail.com>:

> --
> You received this message because you are subscribed to the Google Groups "AngularJS" group.
> To post to this group, send email to ang...@googlegroups.com.
> To unsubscribe from this group, send email to angular+u...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/angular?hl=en.
>
>

Mårten Dolk

unread,
Sep 27, 2011, 7:48:01 AM9/27/11
to ang...@googlegroups.com
Btw, you want to always provide the radix when using parseInt

parseInt('333', 10);

2011/9/27 Mårten Dolk <marte...@gmail.com>:

Suller Andras

unread,
Sep 27, 2011, 7:58:50 AM9/27/11
to ang...@googlegroups.com
On Tue, Sep 27, 2011 at 6:07 PM, Ladislav Prskavec
<ladislav...@gmail.com> wrote:
> I have example: http://jsfiddle.net/abtris/rNTzz/3/
>
> Result is 33,311
>
> But i need 333 + 11 = 344
>
> Is possible make in template?

An ugly solution is like this:
{{items*1 + next*1}}

Better, if you create a new model and display that, but you need to
manually keep this new model up-to-date:
this.sum = parseInt(this.items) + parseInt(this.next)

Or you can create an add() function in your model, and use that in your view:
{{add(items, next)}}

Anyway, it is not angular issue. This is how javascript works when you
add two strings.

Andras

Mårten Dolk

unread,
Sep 27, 2011, 7:58:33 AM9/27/11
to ang...@googlegroups.com
Was a bit quick on the trigger there, if you really want to do the
conversion in the template you could expose parseInt in the scope.

http://jsfiddle.net/YKKqd/

But I would strongly recommend against this! Better to keep this kind
of logic in the controller. Why do you want to add the numbers? Create
a function and name it appropriately and you have testable code :-)


2011/9/27 Mårten Dolk <marte...@gmail.com>:

Igor Minar

unread,
Sep 27, 2011, 8:44:33 AM9/27/11
to ang...@googlegroups.com
lastly, your are dealing with user input that should be converted from string to number you should use formatters: http://docs.angularjs.org/#!/api/angular.formatter.number

/i
Reply all
Reply to author
Forward
0 new messages