[Q#12460482][A#12460596] How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?
https://stackoverflow.com/q/12460482
I tried the following, but got weird results. Why?
Answer
https://stackoverflow.com/a/12460596
Never construct BigDecimals from floats or doubles. Construct them from ints or strings. floats and doubles loose precision. This code works as expected (I just changed the type from double to String):
APIzation
public static void main(String[] args) {
String doubleVal = "1.745";
String doubleVal1 = "0.745";
BigDecimal bdTest = new BigDecimal( doubleVal);
BigDecimal bdTest1 = new BigDecimal( doubleVal1 );
bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("bdTest:"+bdTest); //1.75
System.out.println("bdTest1:"+bdTest1);//0.75, no problem
}
package com.stackoverflow.api;
import java.math.BigDecimal;
public class Human12460596 {
public static String scaleDoublesFromString(
String doubleVal,
String doubleVal1
) {
BigDecimal bdTest = new BigDecimal(doubleVal);
BigDecimal bdTest1 = new BigDecimal(doubleVal1);
bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
return "bdTest:" + bdTest + "; bdTest1:" + bdTest1;
}
}
package com.stackoverflow.api;
import java.math.BigDecimal;
/**
* How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/12460596">https://stackoverflow.com/a/12460596</a>
*/
public class APIzator12460596 {
public static BigDecimal round(String doubleVal, String doubleVal1) {
BigDecimal bdTest = new BigDecimal(doubleVal);
BigDecimal bdTest1 = new BigDecimal(doubleVal1);
bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
// 1.75
System.out.println("bdTest:" + bdTest);
return bdTest1;
}
}