Using Math.round() and cast back to long
Here is sample code to do this conversion :
If you want to learn more about type casting in Java then I also suggest you take a look at Java Fundamentals: The Java Language course on Pluralsight. This is the easiest way to do this conversion. If you want to convert float to int then instead of casting to long you should cast float into an int. It will not do anything special but just discard anything after the decimal point so you will have value 3 in the fromFloat variable.
Since float has a higher range than long, you can cast it to long using typecasting, as shown below : Java supports type casting and that should be the standard way for data type conversion.Īs you know that Java supports type casting and it's also the standard way to convert one data type into another, but you can only typecast higher values into lower. Let's see different approaches to converting a float value to long or int in Java and understand the pros and cons of each approach. It's not costly, you can get it at the cost of a coffee and learn Java better.ģ ways to convert a float to long in Java Btw, If you have just started learning Java or want to fill gaps in your knowledge about Java programming then I suggest you join a comprehensive course like The Complete Java Masterclass on Udemy. In this tutorial, you will learn all three ways to perform float to long conversion in Java. There is no doubt, the second approach is the easiest if the requirement is simply getting rid of anything after a decimal point but if you need rounding then the third approach is the right way to convert a float data type to long in Java. You can also write the Java program by following these tips to convert a float value to an int by replacing the long method with their int counterpart.Īlternatively, you can use Math.round() and then cast back to long data type. This is a more structured way as other ways are simply to cast a float to long or int to get rid of decimal points. The first way to convert a float data type into a long value is to auto-box float primitive into Float object and calls the longValue() method. In short, there are 3 ways to convert a float value into long or int in Java, but we will only focus on the long data type part.
I explained to him how to do that and that's what you will find in this article as well. I asked him whether he needs routing or not, which he wasn't sure but it turns out that he didn't need that. The good thing was that API was returning a float primitive value and you don't need to convert a String to float etc. he was getting "3.144" and he wants to convert it to "3" to store into the database. Yesterday one of the new joiner Java Trainee Engineers from our team came to me and asked about how do you convert a float variable into a long or int data type? He was storing some values coming from another system in the database and only wanted to store values before the decimal point e.g.