Home Java javaTutorial How to convert float to long or int in Java? (with code)

How to convert float to long or int in Java? (with code)

Mar 07, 2019 pm 04:00 PM
java

The content of this article is about how to convert float to long or int in Java? (Attached is the code), which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In Java, there are three ways to convert float to long or int, but we only focus on the long data type part.

The first way to convert a float data type to a long value is to convert the auto-box float primitive to a float object and call the longValue() method.

This is a more structured approach as the other methods simply convert the float to long or int to remove the decimal point.

You can also write a Java program according to the following tips to convert float to int by replacing the long method with the corresponding int method.

Alternatively, you can use Math.round() and then convert it back to the long data type.

The second method is the simplest if you just remove the digits after the decimal point, but if you need to round, then the third method is the best to convert the float data type to long.

In this article, you will learn three ways to perform float to long conversion in Java.

3 ways to convert float to long in Java

Option 1-Casting

Java supports type conversion, which is to convert a A data type is converted to another data type, but only a higher value can be converted to a lower value. Since float has a longer range than long, you can use a type cast to convert it to long like this:

float number = 444.33f; 
long aValue = (long) number; // 444
Copy after login

It won't do anything but discard the value after the decimal point, so it will be in the fromFloat variable Get a value of 3.

If you want to convert float to int, then you should convert float to integer instead of long. This is the simplest conversion method.

Solution 2 - Float.longValue

Another way to convert a float to a long is to first autoload the float value into a Float wrapper object and then call the Float.longValue() method. This method internally converts a floating point value to a long, as shown in the above image and the code below:

public long longValue(){
 return(long)value;
}
Copy after login

Here is how to convert using this method:

Float PIE = 3.14f; 
long fromFloat = PIE.longValue();
Copy after login

When you have a Float object and This method is more appropriate when it is not a float primitive value.

Solution 3 - Math.round and Casting

Sometimes conversion isn't as simple as discarding everything after the decimal point. Rounding may be required before conversion. If this is the case, you can use the Math.round() method to perform rounding first, and then perform type conversion to convert the double to long. The Math.round() method returns a double value. Here is the sample code to achieve this conversion:

// 使用Math.round()并强制转换为long
float points = 333.322f;
long rounded = Math.round(points); 
System.out.printf("float : %f, long : %d %n", points, rounded); 
points = 333.922f; 
rounded = Math.round(points); 
System.out.printf("float : %f, long : %d %n", points, rounded); 
Output : float : 333.321991, long : 333 float : 333.921997, long : 334
Copy after login

You can see the effect of rounding. In the first example, the float is rounded down, which is why the converted long value is 333, And in the second example it is rounded, that's why the long value is 334.

Java program to convert float to long data type

The code below As shown, it combines three methods to convert float to long. You can see how they work and learn how to perform another similar conversion technique such as float to int, short or byte or double to long, int, short and byte.

/** 
* 用于在Java中将float转换为long
* 
* @author Javarevisited 
*/ 
public class FloatToLongConverter{ 

 public static void main(String[] args) { 

 // Autobox浮动到Float然后调用Float.longValue();
 Float PIE = 3.14f; 
 long fromFloat = PIE.longValue(); 

 System.out.printf("float value %f, long value %d %n", PIE, fromFloat); 
 
 // 简单的类型转换来消除小数 
 float number = 444.33f; 
 long aValue = (long) number; 
 System.out.printf("float value %f, after casting into long %d %n", number, aValue); 
 
 // 使用Math.round()并将其转换回long 
 float points = 333.322f; 
 long rounded = Math.round(points); 

 System.out.printf("float : %f, long : %d %n", points, rounded); 
 }
 }
Output : 
float value 3.140000, long value 3 
float value 444.329987, after casting into long 444 
float : 333.321991, long : 333
Copy after login

This is how to convert float to long data type in Java. If you are just removing decimal values, type conversion is the easiest way. This is not the only way to round numbers in Java, but it works for most purposes.

If you want to learn faster and more systematically, come and join the group chat, which includes Alibaba, Baidu interview questions, Java engineering, high performance and distribution, microservices, performance tuning Spring, MyBatis , explanation of Netty source code analysis and other knowledge points [Java Architect Resource Sharing Group] (group number 142019080), directly click the link to join the group. https://jq.qq.com/?_wv=1027&k=5lXBNZ7

The above is the detailed content of How to convert float to long or int in Java? (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles