Display absolute value angularjs

All we need is an easy explanation of the problem, so here it is.

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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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

Method 2

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

Method 3

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)

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply