java.lang.Float longValue()
Description
The longValue() method of Float class is used to get the equivalent of this Float object in long primitive. This method is a little bit tricky to use since the float primitive can handle more precision than long value thus if we will use the this method we might lost the precision the original value has. Let’s say we have the following declaration
Float value = new Float(12.892f);
. Certainly the value 12.892f is still within range of Float but what will happen if we will convert it to long using longValue() method? I will be discussing this thoroughly later on this document.Method Syntax
public long longValue()
Method Returns
The longValue() method of Float class returns value of this Float as a long after a narrowing primitive conversion.
Compatibility
Java 1.0
Discussion
The longValue method is used to transform this Float object to primitive type long. This is basically the core functionality of this method. As we all know a float data type can have decimal digits, what will happen to that if we convert it into long. For example if we have the following expression:
Float value = new Float(12.75f);
. Upon conversion to long, the float value decimal digit will get truncated. Due to data type narrowing, the returned value will be 12.
Java Float longValue() Example
Below is a simple java example on the usage of longValue() method of Float class.
package com.javatutorialhq.java.examples; import java.util.Scanner; import static java.lang.System.*; /* * This example source code demonstrates the use of * longValue() method of Float class. */ public class FloatLongValueExample { public static void main(String[] args) { // Ask user input System.out.print("Enter Desired Value:"); // declare the scanner object Scanner scan = new Scanner(System.in); // use scanner to get value from user console Float userInput = scan.nextFloat(); // close the scanner object scan.close(); // convert the Float input to long long value = userInput.longValue(); out.println("Value in long is " + value); } }
Basically on the above example, we just ask for user input on the console and then we use the scanner object to get the float input. After that we assign the value to an Float wrapper class and we then get the long equivalent of this Float object using the longValue() method.