Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

currency and floating-point arithmetic in Ember.TextField

Tags:

ember.js

I need to be able to handle currencies accurately in my ember app. For example, if my app is tallying a list of items, and the user enters $0.10 for item 1 and $0.20 for item 2, I should be storing the tally value as $0.30, not $0.30000000000000004.

For this, I wanted to convert user inputs into cents behind the scenes but still accept and display them as floating point in the textfields.

What's the best way to intercept input values in Em.TextField?

like image 326
Sean X. Yu Avatar asked Feb 02 '26 20:02

Sean X. Yu


1 Answers

You could use a library like sinful.js to take our the weirdness of floating point arithmetic. Or just use good ole rounding

total: function() {
    var sum = 0;
    this.get('content').forEach(function(item) {
        sum += parseFloat(item.price);
    });
    return (Math.round(sum * 100) / 100).toFixed(2);
}.property('[email protected]')
like image 105
mlienau Avatar answered Feb 05 '26 13:02

mlienau