Re: Formatting BigDecimals
RedGrittyBrick <RedGrittyBrick@SpamWeary.foo> writes:
The following code produces an IllegalArgumentException "Digits < 0"
String.format("%10.2f", new BigDecimal(0.0001));
Here is another test:
public class Main
{ public static void main( final java.lang.String[] args )
{ final java.math.BigDecimal bigDecimal
= new java.math.BigDecimal( "0.001234" );
for( int i = 9; i >= 0; -- i )try
{ final java.lang.String string
= java.lang.String.format( "%%." + i + "f: %." + i + "f", bigDecimal );
java.lang.System.out.println( string ); }
catch( final java.lang.IllegalArgumentException illegalArgumentException )
{ java.lang.System.out.println( illegalArgumentException ); }}}
%.9f: 0,001234000
%.8f: 0,00123400
%.7f: 0,0012340
%.6f: 0,001234
%.5f: 0,00123
%.4f: 0,0012
%.3f: 0,001
%.2f: 0,001234
java.lang.IllegalArgumentException: Digits < 0
java.lang.IllegalArgumentException: Digits < 0
java.util.Formatter creates a new java.math.MathContext.
In the OP's case of "0.0001" with "%10.2f", this will
try to create a math context with a negative precision
?compPrec?, which will result in the throw as follows:
public class Main
{ public static void main( final java.lang.String[] args )
{
final java.math.BigDecimal value
= new java.math.BigDecimal( "0.0001" );
final int precision = 2; /* as given in "%10.2f" */
java.lang.System.out.println( "precision = " + precision );
{ /* as calculated in java.util.Formatter */
final int prec = (precision == -1 ? 6 : precision);
java.lang.System.out.println( "prec = " + prec );
final int scale = value.scale();
java.lang.System.out.println( "scale = " + scale );
int compPrec = value.precision();
if( scale > prec )compPrec -= (scale - prec);
java.lang.System.out.println( "compPrec = " + compPrec );
final java.math.MathContext mathContext =
new java.math.MathContext( compPrec ); }}}
precision = 2
prec = 2
scale = 4
compPrec = -1
Exception in thread "main" java.lang.IllegalArgumentException: Digits < 0
at java.math.MathContext.<init>(Unknown Source)
I have no opinion about whether this is by design or a bug.