Logarithm of a BigDecimal

Java Number Cruncher: The Java Programmer’s Guide to Numerical Computing provides a solution using Newton’s Method. Source code from the book is available here. The following has been taken from chapter 12.5 Big Decimal Functions (p330 & p331): /** * Compute the natural logarithm of x to a given scale, x > 0. */ public … Read more

Using BigDecimal to work with currencies

Here are a few hints: Use BigDecimal for computations if you need the precision that it offers (Money values often need this). Use the NumberFormat class for display. This class will take care of localization issues for amounts in different currencies. However, it will take in only primitives; therefore, if you can accept the small … Read more

Representing Monetary Values in Java [closed]

BigDecimal all the way. I’ve heard of some folks creating their own Cash or Money classes which encapsulate a cash value with the currency, but under the skin it’s still a BigDecimal, probably with BigDecimal.ROUND_HALF_EVEN rounding. Edit: As Don mentions in his answer, there are open sourced projects like timeandmoney, and whilst I applaud them … Read more

ArithmeticException: “Non-terminating decimal expansion; no exact representable decimal result”

From the Java 11 BigDecimal docs: When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.) As a corollary of computing the exact … Read more

How to change the decimal separator of DecimalFormat from comma to dot/point?

You can change the separator either by setting a locale or using the DecimalFormatSymbols. If you want the grouping separator to be a point, you can use an european locale: NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN); DecimalFormat df = (DecimalFormat)nf; Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers … Read more

Double vs. BigDecimal?

A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001) could result in the 0.001 being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen. The disadvantage of BigDecimal is that … Read more