w3resource

Java: Convert a float value to absolute value


Float to Absolute Value

Write a Java program to convert a floating value to an absolute value.

Sample Solution:

Java Code:

import java.util.*;
public class Example9 {

 public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Input a float number: ");
        float  x = in.nextFloat();  
        System.out.printf("The absolute value of %.2f is: %.2f",x, convert(x));
		System.out.printf("\n");
    }

    public static float convert(float n)
	{
		float absvalue = (n >= 0) ? n : -n;
		return absvalue;
	}
}

Sample Output:

Input a float number: 12.53                                            
The absolute value of 12.53 is: 12.53    

Flowchart:

Flowchart: Convert a float value to absolute value.



For more Practice: Solve these Related Problems:

  • Write a Java program to compute the absolute value of a float without using Math.abs.
  • Write a Java program to implement a custom method to return the absolute value of a float and test edge cases.
  • Write a Java program to calculate the absolute value of a float using bit-level operations.
  • Write a Java program to compare a user-defined absolute value function for floats against the built-in method for various inputs.

Go to:


PREV : Integer to Absolute Value.
NEXT : Round Float Value.


Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.