20

I have a string with some numeric value.

I want to format it in a way where hundreds are comma separated and the number is having $ dollar sign before it.

e.g. 12345 should be formatted to $ 12,345.00

I tried the below code without dollar sign:

new java.text.DecimalFormat(#,##0.00).format.(myString)

and the below one with dollar sign:

new java.text.DecimalFormat($ #,##0.00).format.(myString)

However, both are giving error.

What is the right way to achieve this format ?

This is a part of jasper report jrxml where I want to avoid "null" on the report and thus inserting the below code:

<textField isBlankWhenNull="false" isStretchWithOverflow="true">            
  <reportElement stretchType="RelativeToTallestObject" x="1350" y="0" width="150" height="30"/>             
      <textElement/>             
   <textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{myString}!=null?new java.text.DecimalFormat(#,##0.00).format.($F{myString}):"Unavailable"]]></textFieldExpression>        
</textField>

Where myString results from a query and is declared in jrxml as:

 <field name="myString" class="java.lang.String"/>

Earlier myString was declared as BigDecimal, but then comparison operator ?= was not working.

If the currency value is not available, I want to print "unavailable" on the report instead of default "null". Else, I want the number to be properly formatted as described above.

How to resolve this issue?

Thanks for reading.

Vicky
  • 16,679
  • 54
  • 139
  • 232

8 Answers8

43

The correct expression is:

new java.text.DecimalFormat("$ #,##0.00").format(Double.valueOf($P{strParam}))

The working sample for java.lang.Integer and java.lang.String:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="format_as_current" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <parameter name="intParam" class="java.lang.Integer">
        <defaultValueExpression><![CDATA[12345678]]></defaultValueExpression>
    </parameter>
    <parameter name="strParam" class="java.lang.String">
        <defaultValueExpression><![CDATA["12345678.95"]]></defaultValueExpression>
    </parameter>
    <title>
        <band height="79" splitType="Stretch">
            <textField>
                <reportElement x="137" y="18" width="291" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[new java.text.DecimalFormat("$ #,##0.00").format($P{intParam})]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="137" y="48" width="291" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[new java.text.DecimalFormat("$ #,##0.00").format(Double.valueOf($P{strParam} != null && $P{strParam}.length() > 0 ? Double.valueOf($P{strParam}) : 0))]]></textFieldExpression>
            </textField>
        </band>
    </title>
</jasperReport>

The result will be (preview in iReport):

The result in *iReport*

Note: You should also add check for null.

You can also use pattern property of textField for formatting data.

The sample:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="format_as_current" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <parameter name="intParam" class="java.lang.Integer">
        <defaultValueExpression><![CDATA[12345678]]></defaultValueExpression>
    </parameter>
    <parameter name="strParam" class="java.lang.String">
        <defaultValueExpression><![CDATA["12345678.95"]]></defaultValueExpression>
    </parameter>
    <title>
        <band height="148" splitType="Stretch">
            <textField pattern="$ #,##0.00">
                <reportElement x="218" y="99" width="100" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[$P{intParam}]]></textFieldExpression>
            </textField>
            <textField pattern="$ #,##0.00">
                <reportElement x="218" y="119" width="100" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[$P{strParam} != null && $P{strParam}.length() > 0 ? Double.valueOf($P{strParam}) : 0]]></textFieldExpression>
            </textField>
        </band>
    </title>
</jasperReport>

The result will be the same.

Alex K
  • 22,315
  • 19
  • 108
  • 236
  • Thanks Alex, will try it out! – Vicky Jun 06 '12 at 12:56
  • Double.valueOf is giving error " expected"... I found this - "u need to specify the compile class path if ur using libraries external to jasper reports" --- but could not find out how to achieve it! – Vicky Jun 07 '12 at 04:30
  • What tool are you using for testing report (iReport or something else)? Did you set language for report as *Java*? – Alex K Jun 07 '12 at 05:51
  • Alex you should suggest the use of pattern to have correct result in xls export (as number), invert methods?? – Petter Friberg Jan 13 '16 at 19:50
  • Why the currency values does not apply from current locale in Jasper? – zygimantus Oct 25 '16 at 12:34
  • can i ask something,@AlexK regarding this matter? How about if we use another country currency? For example in Indonesia, it use "Rp." Instead of "$" and also the decimal point is using comma instead of dot. – gumuruh Oct 11 '17 at 03:49
3

The above code can work for three cases:

  1. fix two zeros after decimal point. When I tried to use "Double" datatype for this purpose it did not work for me. But this code can do it.
  2. Fix $ -sign before the number in string datatype and also takes care of "-" sign in its own.
  3. Get "," after 3 digits in a number

For me i wanted to put "," comma after every three digits (by passing string as a parameter) and i tried the following code. It did work for me.... Thank you very much. I appreciate this answer.

<textFieldExpression>

<![CDATA[new java.text.DecimalFormat("$ #,##0.00").format(Double.valueOf($P{actualWrittenPremium} != null && $P{actualWrittenPremium}.length() > 0 ? Double.valueOf($P{actualWrittenPremium}) : 0))]]>

</textFieldExpression>
bmu
  • 35,119
  • 13
  • 91
  • 108
Rushi
  • 31
  • 1
3

Just came accross this Problem and found a solution which is working fine for me.

Be Aware - its not exactly what the Autor is asking for but if you google this Problem you will end up here.

I have Servers with German and English Locale and on all the Currency should be like 7.500,60

My final expression:

new java.text.DecimalFormat("#,##0.00", new java.text.DecimalFormatSymbols(java.util.Locale.GERMANY)).format($F{variable}) + " €"

so the Locale Setting is "hardcoded" - exactly what i needed.

Maybe this will help someone

Frankstar
  • 306
  • 1
  • 3
  • 10
  • if the country locale definition is not given over there? How to make it anyway? For example, Indonesia is not listed inside java.util.Locale. @Frankstar – gumuruh Oct 11 '17 at 03:52
  • @gumuruh you can use new java.util.Locale, ex: for Brazil, I use `new java.util.Locale("pt", "BR")` – Saureco Mar 25 '20 at 20:05
3

Using DecimalFormat is not optimal. For formatting currencies, we should use NumberFormat. With NumberFormat we are way more flexible; we can set dynamically the current locale and the currencies are automatically adapted to the selected locale.

<![CDATA[ NumberFormat.getCurrencyInstance($P{REPORT_LOCALE}).format($F{price}) ]]>

We can set the locale with the REPORT_LOCALE parameter

def params = [REPORT_LOCALE: new Locale("sk", "SK")]
def jrPrint = JasperFillManager.fillReport(jrReport, params, ds)

or with the net.sf.jasperreports.default.locale property.

net.sf.jasperreports.default.locale=sk_SK

see https://zetcode.com/jasperreports/formatcurrency/ for a working example.

Jan Bodnar
  • 10,969
  • 6
  • 68
  • 77
1

Im using iReport 5.6.0 and I took some of these answers but what It worked for me was:

Text Field (I put this into the designer):

Float.valueOf($V{DISPONIBLE_FINAL})

And in the Pattern (into properties tab), I used Custom Format with:

$#,##0.00

Putting all the string mentioned here in a whole "Edit expression" field didnt worked for me.

Hope It helps.

PD: I was using groovy jar that is the compatible with jasper 5.6.0 checked in mvnrepository site.

Rodolfo Velasco
  • 845
  • 2
  • 12
  • 27
0

When trying the recommended answer in iReport, I got "illegal string body character after dollar sign;" when I ran the report.

Easily remedied by escaping the dollar sign with a backslash like so:

new java.text.DecimalFormat("\$ #,##0.00").format(Double.valueOf($F{le1_feeAmount}))
incircuitous
  • 131
  • 6
0

You can do this also using the iReport Studio. In the studio click on the field and see the properties pane.In properties pane under Text Field Properties you'll find the Pattern property. Paste #,##0.00 or click on the three dots and tick the check box in the popup menu to separate at 1000.

Gayan Kavirathne
  • 2,909
  • 2
  • 18
  • 26
0

The problem is the locale, this works for me:

     new java.text.DecimalFormat("#,##0.00", new DecimalFormatSymbols(Locale.ENGLISH)).format(Double.valueOf($F{7}))
polypiel
  • 2,321
  • 1
  • 19
  • 27