How do I get the absolute value of a number?

The example below show you how to get the absolute value of a number. To get the absolute value or the abs value of a number we use the Math.abs() method call. The Math.abs() method is an overloaded that can accept value in type of double, float, int or long.

package org.kodejava.example.math;

public class GetAbsoluteValueExample {
    public static void main(String[] args) {
        Double value = -10.0D;

        double abs1 = Math.abs(value);
        System.out.println("Absolute value in double: " + abs1);

        float abs2 = Math.abs(value.floatValue());
        System.out.println("Absolute value in float : " + abs2);

        int abs3 = Math.abs(value.intValue());
        System.out.println("Absolute value in int   : " + abs3);

        long abs4 = Math.abs(value.longValue());
        System.out.println("Absolute value in long  : " + abs4);
    }
}

The code snippet above print the following result:

Absolute value in double: 10.0
Absolute value in float : 10.0
Absolute value in int   : 10
Absolute value in long  : 10
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply