DEV Community

Cover image for Truncate Decimals Manually in Java
Edwin Torres
Edwin Torres

Posted on • Edited on

Truncate Decimals Manually in Java

Given a floating-point number 100.899456, how would you truncate it to just two decimals?

In other words, how would you convert that number to 100.89?

You can do this in Java without using a function call. Here’s the algorithm:

  1. Multiply the original number by 100 to move the decimal point to the right two places.
  2. Cast the result to an integer to remove the remaining decimal places.
  3. Divide the result by 100.0 to move the decimal point back to the left two places.

Here’s the full code:

public class Main {  
  public static void main(String args[]) { 
    double x = 100.899456;
    double y = (int) (x * 100) / 100.0;
    System.out.println("before: " + x);
    System.out.println("after:  " + y);
  } 
}
Enter fullscreen mode Exit fullscreen mode

And here’s the output:

before: 100.899456
after:  100.89
Enter fullscreen mode Exit fullscreen mode

Thanks for reading! 😀

Follow me on Twitter @realEdwinTorres for more programming tips and help.

Top comments (0)