Sobes.tech
Junior — Middle

Which data format is most suitable for representing monetary amounts in a program?

sobes.tech AI

Answer from AI

The most suitable data type for representing monetary amounts in Java is the BigDecimal class. It allows working with floating-point numbers with high precision and avoids rounding errors that often occur when using float or double types.

Example of usage:

import java.math.BigDecimal;

public class MoneyExample {
    public static void main(String[] args) {
        BigDecimal price = new BigDecimal("19.99");
        BigDecimal quantity = new BigDecimal("3");
        BigDecimal total = price.multiply(quantity);
        System.out.println("Total: " + total); // Total: 59.97
    }
}

Using BigDecimal with a constructor from a string helps avoid decimal representation errors.

Which data format is most suitable for representing… - sobes.tech