35

Is there a way to use math functions in angular2 bindings?

example

<div class="partition-panel">
                <b class="pull-left">{{Math.round(variable/12*2)}}</b>
                <b class="pull-right">{{Math.round(variable/12*2)}}</b>
 </div>

when try to use this i got error

Cannot read property 'round' of undefined

Also the similar question is answered for angular1

Community
  • 1
  • 1
Jagadeesh Govindaraj
  • 6,977
  • 6
  • 32
  • 52
  • 1
    The problem is, from the template you only have access to the local scope of your `Component`, so you either have to define a helper method or assign `window.Math` to a member variable like Adrien suggested. – Maximilian Riegler Nov 16 '16 at 13:16

2 Answers2

84

You can try this :

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{math.round(number)}}</h2>
    </div>
  `,
})
export class App {
  number = 2.5;
  math = Math;
}

DEMO

Vega
  • 27,856
  • 27
  • 95
  • 103
Adrien BARRAL
  • 3,474
  • 1
  • 25
  • 37
  • This worked, but I had to move the declaration to the component whose template needed Math. – RSinohara Jan 25 '17 at 14:40
  • 4
    You should be also able to avoid init Math on the constructor and simply write: Math: Math = Math; – 39ro Dec 21 '17 at 13:58
13

For rounding numbers in Angular templates, you can use the DecimalPipe: {{ value | number }}

See all the rounding options in https://angular.io/api/common/DecimalPipe

For all the built-in pipes, check https://angular.io/api?type=pipe

Anis Abboud
  • 1,328
  • 2
  • 16
  • 23
  • This should be the accepted answer as it makes use of pipes instead of using functions in template bindings. Also less code needed than declaring Math as a variable. – Simplicity's_Strength Jun 07 '20 at 19:32
  • Careful though, as the rounding done by the pipe is different for negative numbers. – bigstones Feb 11 '21 at 08:29
  • 1
    There are no real rounding options though. This [only rounds "to-nearest" per the docs](https://angular.io/api/common/DecimalPipe#digitsinfo) and does not replace `floor()` or `ceil()`. – vlz Feb 09 '22 at 14:46