Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to round a floating-point number to an integer in Java

2 Answers

0 votes
public class RoundFloatingPoint {
    public static void main(String[] args) {
        float x = 9382.4f;
        long y = Math.round(x);
        System.out.println(y);
        
        x = 9382.5f;
        y = Math.round(x);
        System.out.println(y);
    }
}



/*
run:

9382
9383

*/

 



answered May 14, 2025 by avibootz
0 votes
import java.text.NumberFormat;
import java.math.RoundingMode;

public class RoundFloatingPoint {
    public static void main(String[] args) {
        // large numbers include commas for readability (e.g., "9,382"). 
        // When you try to parse this formatted string into an integer using Integer.parseInt(), 
        // it fails because "9,382" is not a valid integer representation 
        // (commas are not allowed in number parsing).
        
        // Define floating-point value to round
        double x = 938.4;

        // Initialize NumberFormat instance
        NumberFormat f = NumberFormat.getNumberInstance();
        f.setRoundingMode(RoundingMode.HALF_UP);
        f.setMaximumFractionDigits(0);

        // Format the rounded number correctly
        String roundedStr = f.format(x);
        int y = Integer.parseInt(roundedStr); // Convert formatted string to integer
        System.out.println("Rounded value: " + y);
        
        x = 938.5;
        // Format the rounded number correctly
        roundedStr = f.format(x);
        y = Integer.parseInt(roundedStr); // Convert formatted string to integer
        System.out.println("Rounded value: " + y);
        
    }
}



/*
run:

Rounded value: 938
Rounded value: 939

*/

 



answered May 14, 2025 by avibootz
edited May 14, 2025 by avibootz

Related questions

1 answer 42 views
2 answers 58 views
1 answer 45 views
2 answers 151 views
1 answer 128 views
1 answer 130 views
...