I'm new to Java and stuck at an issue. below is the sample program i made for the same.
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Currency;
import java.util.Locale;
import java.math.RoundingMode;
import java.math.BigDecimal;
public class Main {
public static void main(String[] args)
{
Object fieldVal = null;
// Create the DecimalFormat Instance
DecimalFormat deciFormat = new DecimalFormat();
String valStr = "31363.214722222422";
deciFormat.setMaximumFractionDigits(15);
try {
fieldVal = new BigDecimal(deciFormat.parse(valStr).toString());
}
catch (java.text.ParseException e){
}
System.out.println(fieldVal);
}
}
Here I'm expecting the output as 31363.214722222422
but instead I'm getting 31363.214722222423
.
I observed that this rounding up happens for 12th decimal place. If I use till 11 decimal place, it works absolutely fine.
I even tried to avoid rounding up with deciFormat.setRoundingMode(RoundingMode.DOWN);
, but it didn't work.
Need some guidance to solve this issue.
CodePudding user response:
Don't use DecimalFormat because it will use double
internally. Instead parse it directly using new BigDecimal(String)