I'm using Java 1.6. For the purposes of writing the "cents" from a
BigDecimal in a special way on a JSP page, how do I extract only the
two decimal places from a BigDecimal number? For example, if my
number is
123.45123
I want to get the number "45" (the two numbers after the decimal
place) into a string. Rounding is not important. Thanks, - Dave
Does x.reminder(BigDecimal.ONE).setScale(2) work?
Arne
No.
Exception in thread "main" java.lang.ArithmeticException: Rounding necessary
at java.math.BigDecimal.divideAndRound(BigDecimal.java:1435)
at java.math.BigDecimal.setScale(BigDecimal.java:2381)
at java.math.BigDecimal.setScale(BigDecimal.java:2428)
at test.BigDecimalTest.main(BigDecimalTest.java:26)
Java Result: 1
Use the JSTL :
<fmt:formatNumber value="${myBigDecimal}" pattern="#.00"/>
JB.
I don't know the quickest JSP. I assume that Jean-Baptiste idea isn't
going to work because you want "45" not "123.45"
Here's a Java way of doing it. Might be considered evil in a JSP.
public class BigDecimalTest {
public static void main( String[] args )
{
BigDecimal test = new BigDecimal( "123.456789" );
BigDecimal oneHundred = new BigDecimal( "100" );
System.out.println( test.subtract( test.divideToIntegralValue(
BigDecimal.ONE ) ).multiply( oneHundred ).
divideToIntegralValue( BigDecimal.ONE )
.stripTrailingZeros());
}
}
Feels like a kludge, but this might work for you:
public class Main
{
public static void main(String[] args)
{
BigDecimal bd = new BigDecimal(4096.4567890);
String textBD = bd.toString();
int radixLoc = textBD.indexOf('.');
System.out.println("Cents: " + textBD.substring
(radixLoc + 1, radixLoc + 3));
}
}
x.reminder(BigDecimal.ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
Arne
> x.reminder(BigDecimal.ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
Closer. It's "remainder" of course, not "reminder". And in my test I
had a 6 after the 45, so this actually gave .46 not .45, although the OP
did say rounding was not an issue. I think you still have to get rid of
the decimal place to meet the OP's requirements though.
BigDecimal test = new BigDecimal( "123.456789" );
System.out.println( test.remainder(BigDecimal.ONE).setScale(2,
BigDecimal.ROUND_HALF_UP ).movePointRight( 2 ) );
Prints "46" and seems to be closest to what the OP is asking for. Good
job spotting that seScale has a rounding mode readily available. For
some reason, "round()" doesn't.
Oops. Indeed. I read the OP's question a bit too quickly. Sorry.
JB.
Yup.
:-)
Arne
Where I come from ROUND_HALF_UP is the default.
> I think you still have to get rid of the
> decimal place to meet the OP's requirements though.
>
> BigDecimal test = new BigDecimal( "123.456789" );
>
> System.out.println( test.remainder(BigDecimal.ONE).setScale(2,
> BigDecimal.ROUND_HALF_UP ).movePointRight( 2 ) );
>
> Prints "46" and seems to be closest to what the OP is asking for.
Or just substring to get rid of that period.
Arne