## 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.

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);
}
}
``````

And hereβs the output:

``````before: 100.899456
after:  100.89
``````