moevans
moevans

Reputation: 319

Calculate Sale Prices in Angular JS

So I have a simple form that provides a product cost, markup and final sale price.

However, angularjs is not returning the correct value for what I am providing it.

Consider the following:

I have a product that costs me $50.00 to get in my store.

To make a profit, I mark this product up 30% or .30.

So my final sale price to my customers would be $65.00

To figure this out we use a simple math calculation like so:

Item Cost + (Item Cost x Markup Percentage) = Price 

$50.00 + ($50.00 x .30) = $65.00

So in my HTML I have a simple form

<form>
  <input type="text" ng-model="pr.cost" class="form-control" placeholder="Cost" />
  <input type="text" ng-model="pr.markup" class="form-control" placeholder="Markup %" />
  <input type="text" class="form-control" placeholder="{{pr.type}} Sale" value="{{pr.cost+(pr.cost*pr.markup)|currency}}" readonly/>
</form>

When the numbers I gave above are entered into this form, I get the following as a result:

Cost: $50
Markup: .30
Sale Price: $5,015.00

That's quite the 30% markup! What in the world am I doing wrong here?

For those that love fiddles, I've create a JSFiddle here: http://jsfiddle.net/p20roLLu/

Upvotes: 0

Views: 1601

Answers (2)

Gregory Wullimann
Gregory Wullimann

Reputation: 567

It looks like that the problem is the +. At the moment the you are getting:

50 + (50*.3) = 50+15 -> 5015 -> $5,015

As you can

value="{{pr.cost*1+(pr.cost*pr.markup)|currency}}"

For a clenear versione you should use parseInt():

How can I parse String to Int in an Angular expression?

Upvotes: 0

GoogleBen
GoogleBen

Reputation: 28

This is because JavaScript is taking in pr.cost as a String. It sees (pr.cost*pr.markup) and automatically converts to an integer type, but pr.cost throws it off so it adds "50"+"15" and returns "5015". This can be solved by forcing JavaScript to interpret pr.cost as an integer, an easy way being to multiply or divide by one:

{{(pr.cost*1)+(pr.cost*pr.markup)|currency}}

This is not a perfect or clean solution, but it will at least work.

Upvotes: 1

Related Questions