23

I am getting a negative number from JSON object. I want to remove "-" form that negative number and only display the absolute value.

Received json:

{
    "value": -2.34
}

What I want to show:

The value is: 2.34

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
Abhishek Kumar
  • 328
  • 1
  • 4
  • 13
  • 4
    Try `Math.abs(-2.34);` – Thamilhan Dec 08 '15 at 04:52
  • In your case - is not a symbol. Its a sign. – Vivek Dec 08 '15 at 04:59
  • Your question has changed, namely, the number format. In this regard, you can rewrite the filter like this `return function(num) { return Math.abs(num.value) }` and after that use it in html such way `{{ {"value": "-2.34"} | makePositive }}` – fedorshishi Dec 08 '15 at 08:37

3 Answers3

32

You can use angular filter

js file

angular.module('myApp',[]).filter('makePositive', function() {
    return function(num) { return Math.abs(num); }
});

html file

{{ (-12) | makePositive }}
{{ (2) | makePositive }}

output

12 2

fedorshishi
  • 1,467
  • 1
  • 18
  • 34
8

You can use JavaScript supported built-in Math object for getting absolute value.

Math.abs(-2.34)

The Math.abs() function returns the absolute value of a number

Reference

Vivek
  • 11,938
  • 19
  • 92
  • 127
1
Math.abs(number)

This will get you the absolute value of any number you put in there, including the removal of any leading zeroes.

Additionally, you can also do this:

parseInt(number, 10)