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,872 questions

51,796 answers

573 users

How to truncate a double to removes the fractional part in Java

2 Answers

0 votes
package javaapplication1;
 
public class JavaApplication1 {
 
    public static void main(String[] args) {
 
        try {
 
            double d1 = 3.1415;
            double d2 = -2.789;
 
            System.out.println(Math.floor(d1));
            System.out.println(Math.floor(d2));
 
            System.out.println(Math.round(d1));
            System.out.println(Math.round(d2));
 
            // Casting to int will remove the fractional part
            // Truncate the number
            System.out.println((int) d1);
            System.out.println((int) d2);
 
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}
 
/*
                   
run:
      
3.0
-3.0
3
-3
3
-2
          
 */

 



answered Dec 16, 2016 by avibootz
edited Dec 16, 2016 by avibootz
0 votes
package javaapplication1;

public class JavaApplication1 {

    static double truncate(double d) {
        if (d < 0) {
            return Math.ceil(d);
        } else {
            return Math.floor(d);
        }
    }

    public static void main(String[] args) {

        try {

            double d1 = 3.1415;
            double d2 = -2.789;

            System.out.println(Math.floor(truncate(d1)));
            System.out.println(Math.floor(truncate(d2)));

        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}

/*
                  
run:
     
3.0
-2.0
         
 */

 



answered Dec 16, 2016 by avibootz

Related questions

3 answers 151 views
1 answer 147 views
1 answer 85 views
1 answer 98 views
1 answer 120 views
120 views asked Nov 3, 2020 by avibootz
...