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 181 views
1 answer 173 views
1 answer 111 views
111 views asked Jan 10, 2024 by avibootz
1 answer 127 views
127 views asked Jan 5, 2023 by avibootz
1 answer 141 views
141 views asked Nov 3, 2020 by avibootz
...