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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

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

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles