K
K
Kostya Bakay2016-04-23 17:45:14
Java
Kostya Bakay, 2016-04-23 17:45:14

How to leave two numbers after the decimal point in double?

There is a method that works with numbers and returns a double as a result. It is necessary that it return a number in which there are no more than two digits after the decimal point, that is, truncate (do not round!). All I've found are String cast operations like String.format or DecimalFormat, but I want the method to return a trimmed double, not a String. Can you suggest how to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2016-04-23
@kostyabakay

you have "123.456789"
do "12345.6789" multiplying by 100
do 12345 using floor - rounding to the integer part by discarding the fractional. You can try using int() - you just need to get rid of the extra fractional part.
do 123.45 divided by 100
d = (Double)Math.floor(d*100)/100.0;

B
bromzh, 2016-04-23
@bromzh

Exactly - no way, there will be rounding errors. Fixed precision numbers require BigDecimal.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question