eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In Java programming, it’s common to face the need to convert a floating-point value to an integer. Since float allows decimal values, whereas int only holds whole numbers, converting between them can often lead to precision loss. It’s important to understand the different conversion techniques available to ensure our programs perform accurately.

In this article, we’ll look at various methods for converting a float to an int in Java, along with practical examples that demonstrate when each approach is appropriate.

2. float and int in Java

Let’s start by looking at the differences between float and int in Java:

  • The float is a 32-bit data type used for representing numbers that have fractions. It follows the IEEE 754 standard and is suitable when we need a wide range of values, especially those involving decimals.
  • On the other hand, int is also a 32-bit data type but only represents whole numbers. It’s perfect for tasks that require only integers, like counting items or representing positions in an array.

When converting a float to an int, we need to keep in mind that this conversion will remove the fractional part, leading to a potential loss of accuracy. The method we choose to convert a float to an int depends on how we want to handle that fractional portion.

3. Methods of float to int Conversion

There are several methods for converting a float to an int in Java. Each method handles the fractional component differently, and we need to pick the one that best suits our application’s requirements.

3.1. Explicit Type Casting

The most straightforward way to convert a float to an int is to use explicit type casting. By placing (int) in front of the float value, we forcefully convert it to an integer. This type of conversion simply removes the decimal part without rounding.

Let’s demonstrate this with a unit test:

@Test
public void givenFloatValues_whenExplicitCasting_thenValuesAreTruncated() {
    int intValue1 = (int) 7.9f;
    int intValue2 = (int) 5.4f;
    int intValue3 = (int) -5.1f;

    assertEquals(7, intValue1);
    assertEquals(5, intValue2);
    assertEquals(-5, intValue3);
}

In this example, we can see that the value 7.9 is converted to 7, the value 5.4 is converted to 5, and -5.1 is converted to -5. The decimal portion is truncated, which means this method is effective when we’re only interested in the integer part and don’t care about rounding.

3.2. Using Math.round()

If we need to convert a float to an int while rounding to the nearest whole number, we can use the Math.round() method. This method handles the decimal value appropriately and rounds up or down based on its value.

To demonstrate this with a unit test, we can use the following code:

@Test
public void givenFloatValues_whenRounding_thenValuesAreRoundedToNearestInteger() {
    int roundedValue1 = Math.round(7.9f);
    int roundedValue2 = Math.round(5.4f);
    int roundedValue3 = Math.round(-5.1f);

    // Then
    assertEquals(8, roundedValue1);
    assertEquals(5, roundedValue2);
    assertEquals(-5, roundedValue3);
}

In this example, the value 7.9 is rounded to 8, the value 5.4 is rounded to 5, and -5.1 is rounded to -5. This approach is useful when we want the closest integer representation, allowing for a more accurate conversion without always rounding down or up.

3.3. Using Math.floor() and Math.ceil()

In scenarios where we need greater control over the rounding behavior, Java’s Math class provides two useful methods:

  • The Math.floor() method consistently rounds a given float value down to the nearest whole number.
  • Conversely, Math.ceil() rounds a float value up to the nearest whole number.

To illustrate how these methods can be used in practice, we can look at a couple of unit tests:

@Test
public void givenFloatValues_whenFlooring_thenValuesAreRoundedDownToNearestWholeNumber() {
    int flooredValue1 = (int) Math.floor(7.9f);
    int flooredValue2 = (int) Math.floor(5.4f);
    int flooredValue3 = (int) Math.floor(-5.1f);

    assertEquals(7, flooredValue1);
    assertEquals(5, flooredValue2);
    assertEquals(-6, flooredValue3);
}

@Test
public void givenFloatValues_whenCeiling_thenValuesAreRoundedUpToNearestWholeNumber() {
    int ceiledValue1 = (int) Math.ceil(7.9f);
    int ceiledValue2 = (int) Math.ceil(5.4f);
    int ceiledValue3 = (int) Math.ceil(-5.1f);

    assertEquals(8, ceiledValue1);
    assertEquals(6, ceiledValue2);
    assertEquals(-5, ceiledValue3);
}

In these tests:

  • The Math.floor() method converts 7.9 to 7, 5.4 to 5, and -5.1 to -6.
  • The Math.ceil() method converts 7.9 to 8, 5.4 to 6, and -5.1 to -5.

Utilizing these approaches allows us to maintain consistency in how our conversions are rounded. This control is important when the rounding direction affects functionality, such as defining thresholds or handling aspects of the user interface.

4. Potential Issues with Conversion

When converting a float to an int, there are a few issues that we should be mindful of:

4.1. Loss of Precision

A key concern is the loss of precision. Since float values can include decimal parts, converting them into int results in the fractional portion being discarded. This truncation can lead to inaccuracies, especially in applications where the exact value is important.

4.2. Overflow Concerns

Another possible issue is overflow. Though both float and int are 32-bit types, they represent different value ranges. A float can store very large numbers, while int values are limited to just over two billion. If we attempt to convert a float that exceeds this range into an int, we may encounter overflow, leading to incorrect or unexpected outcomes.

4.3. Rounding Decisions

Each conversion method has its rounding behavior, and understanding these differences is crucial. For instance, using (int) simply truncates the value, whereas methods like Math.round(), Math.floor(), and Math.ceil() follow different rounding rules. Choosing the correct method is important to prevent bugs or inaccuracies, especially when rounding requirements are strict.

5. Conclusion

Converting float values to int in Java is a routine operation, but it necessitates careful consideration to maintain precision.

Whether we opt for explicit casting to truncate the value, utilize Math.round() for rounding to the nearest integer, or employ Math.floor() and Math.ceil() to consistently round either down or up, each method serves a distinct purpose and carries its implications.

By choosing the right approach according to our specific requirements, we can ensure that our programs manage numeric data effectively and accurately.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)