DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,864 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Truncate Decimals Manually in Java
Edwin Torres
Edwin Torres

Posted on • Updated 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)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.