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

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

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;
}

Here is how to convert using this method:

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

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

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

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
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor