Search code examples
angularjsangular-filters

How to get whole part of decimal number in AngularJS bindings


I want to take the whole part of decimal in the price of book. But when I use Price | number:0 AngularJS rounds the whole part. For instance, if the price is 45.89 it prints the price in browser 46. So, how to make it print just 45 ?

<li class="book-price">{{Price | number:0 }}
    <sup style="font-size: 55%;">
        {{ !((Price*100)%100) ? "00" : (Price*100)%100}}
    </sup>&#8380;
</li>

Solution

  • If you provide number filter with 0 fractionSize Angular will round to nearest whole number. You can create your own filter as answered by R.J.

    OR You can do a math trick. If you subtract 0.5 from your number, Angular will have as you want:

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app>
    {{45.89 | number: 0}}<br>
    {{45.03 | number: 0}}<br>
    {{45.89 - 0.5 | number: 0}}<br>
    {{45.03 - 0.5 | number: 0}}<br>
    </div>