Re: Groovy way to format BigDecimal with thousands separator [SOLUTION]

View: New views
2 Messages — Rating Filter:   Alert me  

Re: Groovy way to format BigDecimal with thousands separator [SOLUTION]

by Michael Potter-3 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On Tue, Oct 27, 2009 at 10:51 AM, Michael Potter <pottmi@...> wrote:

> On Tue, Oct 27, 2009 at 10:46 AM, Jochen Theodorou <blackdrag@...> wrote:
>> Michael Potter schrieb:
>>>
>>> Groovy Crew,
>>>
>>> What are my options to format a BigDecimal with commas?
>>>
>>> I see code using DecimalFormat( "#,###,###,##0.00" ), but
>>> DecimalFormat requires the BigDecimal be converted to double and I do
>>> not want to take the chance of changing the original number.
>>
>> DecimalFormat has also an Object taking format method you can use here
>>
>> bye blackdrag
>>
>> --
>> Jochen "blackdrag" Theodorou
>> The Groovy Project Tech Lead (http://groovy.codehaus.org)
>> http://blackdragsview.blogspot.com/
>>
>
>
> Jochen,
>
> Are you saying that the DecimalFormat(Object) constructor will take a
> BigDecimal?
>
> --
> Michael Potter
>

Thank you Jochen,

This worked:

BigDecimal bd = new BigDecimal("123456.798")
def df = new java.text.DecimalFormat("#,###,###,##0.00" )
String s = df.format(bd)
assert s == "123,456.80"

Sorry about the hard coded types, but I want to make sure that the
numbers are not converted to double.

--
Michael Potter

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



Re: Groovy way to format BigDecimal with thousands separator [SOLUTION]

by Russel Winder-4 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On Tue, 2009-10-27 at 11:19 -0400, Michael Potter wrote:
[ . . . ]
> BigDecimal bd = new BigDecimal("123456.798")
> def df = new java.text.DecimalFormat("#,###,###,##0.00" )
> String s = df.format(bd)
> assert s == "123,456.80"
>
> Sorry about the hard coded types, but I want to make sure that the
> numbers are not converted to double.

All floating point literals and values are BigDecimal by default -- you
actually have to work very hard to get doubles in Groovy.

        def bd = 123456.798
        assert bd.class == BigDecimal
        def df = new java.text.DecimalFormat ( '#,###,###,##0.00' )
        def s = df.format ( bd )
        assert s == "123,456.80"

--
Russel.
=============================================================================
Dr Russel Winder      Partner
                                            xmpp: russel@...
Concertant LLP        t: +44 20 7585 2200, +44 20 7193 9203
41 Buckmaster Road,   f: +44 8700 516 084   voip: sip:russel.winder@...
London SW11 1EN, UK   m: +44 7770 465 077   skype: russel_winder


signature.asc (204 bytes) Download Attachment