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:
- Multiply the original number by 100 to move the decimal point to the right two places.
- Cast that result to an integer to remove the remaining decimal places.
- Divide that result by 100.0 to move the decimal point back to the left two places.
Here’s a sample Java program that does this:
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
Thanks for reading! 😀
Follow me on Twitter @realEdwinTorres for more programming tips and help.