0

Does Java have a BigDecimal set abbreviation?

This is for float. What is for BigDecimal?

import java.math.BigDecimal;

data.setPaymentAmount(25F);
mattsmith5
  • 540
  • 4
  • 29
  • 67
  • 4
    `new BigDecimal("25")` or `BigDecimal.valueOf(12)` - see [documentation](https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/math/BigDecimal.html) for all methods and constructors (it is not a primitive type, nor has it some *abbreviation* {e.g. like primitives or `String`}) - available literals: [JLS 3.10 Literals](https://docs.oracle.com/javase/specs/jls/se18/html/jls-3.html#jls-3.10) – user16320675 Aug 10 '22 at 21:50
  • 5
    No. No it doesn't. – Dawood ibn Kareem Aug 10 '22 at 21:51
  • What you are asking about is a **literal** not an "abbreviation". (And the answer is still No.) – Stephen C Aug 11 '22 at 00:35

1 Answers1

0

tl;dr

Replace your float numeric literal with passing text to a constructor.

data.setPaymentAmount( new BigDecimal( "25" ) );

Details

The first word in the Javadoc for BigDecimal is “immutable”. So you cannot change the number content of such an object. Calling methods such as add, subtract, multiply, and divide result in a new separate BigDecimal object being instantiated.

Never use a float/Float or double/Double as seen in your code, not if you care about accuracy. Those floating point types trade away accuracy for speed of performance. The BigDecimal class does the opposite, trading away speed for accuracy.

Your example code uses a float literal: 25F. Passing a float to the constructor of BigDecimal defeats the purpose of using a BigDecimal if your purpose is accuracy.

To maintain accuracy, use String inputs.

BigDecimal x ;                 // Null object reference. No number involved.
x = new BigDecimal( "25" ) ;   // Representing *exactly* twenty-five in a new object of type `BigDecimal`. 

In your code, if your set… method is meant to install a BigDecimal object, pass a BigDecimal object.

data.setPaymentAmount( new BigDecimal( "25" ) ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • *"The BigDecimal class does the opposite, trading away speed for accuracy."* - Caveat: even so you will still be forced to sacrifice accuracy in some cases; e.g. divisions producing a recurring fraction (in base 2). – Stephen C Aug 11 '22 at 00:31