Formatting currencies and decimal places

I'm currently using NumberFormat.getCurrencyInstance() to format numbers as currency. However, one problem I'm having is that I'd like values with no cents to be formatted with no decimal places, and any values with cents to be formatted with the usual 2 decimal places. For example:
17 would be formatted as $17
17.45 would be formatted as $17.45
17.4 would be formatted as $17.40
The last one is the tricky part--I've tried formatter.setMinimumFractionDigits(0), and this works great for the first two cases. But for the last case, the number gets formatted as $17.4.
Basically my problem is I want a number to be formatted with zero or two decimal places and nothing in between. Is there an easy way to do this?
Thanks in advance.

Otherwise you are likely to find that you are getting .00 due to errors from previous calculations. You are right. Adjusted it to Locale aware
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;
public class SpecialCurrencyFormat extends NumberFormat {
    private static final long serialVersionUID = 1L;
    private final NumberFormat noDecimals;
    private final NumberFormat decimals;
    private final double maxDifference;
    private final double factor;
    public SpecialCurrencyFormat() {
     this(Locale.getDefault());
    public SpecialCurrencyFormat(Locale locale) {
     decimals = NumberFormat.getCurrencyInstance(locale);
     noDecimals = NumberFormat.getCurrencyInstance(locale);
     noDecimals.setMaximumFractionDigits(0);
     maxDifference = Math.pow(10, -decimals.getMaximumFractionDigits()) * .5;
     factor = Math.pow(10, decimals.getMaximumFractionDigits());
    @Override
    public StringBuffer format(double number, StringBuffer toAppendTo,
         FieldPosition pos) {
     double adjustedValue = (Math.round(number * factor)) / factor;
     if ((Math.abs(number - Math.round(number)) < maxDifference)) {
         return noDecimals.format(adjustedValue, toAppendTo, pos);
     } else {
         return decimals.format(adjustedValue, toAppendTo, pos);
    @Override
    public StringBuffer format(long number, StringBuffer toAppendTo,
         FieldPosition pos) {
     return noDecimals.format(number, toAppendTo, pos);
    @Override
    public Number parse(String source, ParsePosition parsePosition) {
     return decimals.parse(source, parsePosition);
    public static void main(String[] args) {
     NumberFormat nf = new SpecialCurrencyFormat(Locale.US);
     double[] values = { 10000, 1000, 100, 10, 1, 10.1, 10.01, 10.001,
          10.002, 10.003, 10.004, 10.005, 10.006, 10.007, 10.008, 10.009,
          10.010 };
     for (double value : values) {
         print(nf, value);
    private static void print(NumberFormat nf, double number) {
     String formatted = nf.format(number);
     try {
         System.out.println(number + "\tas " + formatted + "\tand back "
              + nf.parse(formatted));
     } catch (ParseException e) {
         e.printStackTrace();
}The value adjustedValue is needed since NumberFormat doesn't seem to round the value. It just breaks.
Piet

Similar Messages

  • Download reported data in Tunisian currency (three decimal places)

    Dear all,
    if I use the download of reported data functionalety in EC-CS (TC cx3d1) and the file format is .txt, the system can not handle the three decimal places of tunesian currency and moves the comma one digit to the left side. The values are multiplied with 10 right now.
    Do I need to change the settings somewhere or is that a known problem?
    Many thanks in advance,
    Andrea Reinecke

    Hello,
    many thanks for the quick answer. Maybe I need to specify the problem a little bit: The Tunisian currency has been set to three decimal places. The databaselist shows the values correctly, e.g. 5000,000.
    If I use transaction cx3d1 to download the values, the system converts this value into a textfile. The problem is, that the values is not 5000,00 any longer, instead of 50000. That means, everything is multiplied with 10 and the decimal places are away.
    Do you know that problem? We have it only with the tunisian dinar, but not with the Hungarian currency, which has as well three decimal places.
    Best regards and many thanks in advance,
    Andrea Reinecke

  • Decimal format to 2 decimal places ????

    Hello Everyone,
    I have created a web dynpro application which to display a report depending on the data given by the BAPI. But there is some issue with the numeric data returned by the BAPI.
    For ex - if the BAPI returns 5.00 the value is displayed in the report as 5.
    I want uniform decimal values till 2 decimal places. For example 5 shd come as 5.00, 2.1 shd come as 2.10 etc.
    I searched SDN abt this, and found many threads relating to this.
    I tried using decimal format, creating a simple dictinary type, but using all this what happens is the value basically changes to a string format, this implies that the value is displayed in the table as "left-aligned".
    Where- as we need the decimal numeric values to be right-aligned.
    Any thoughts how to achieve this.
    Please correct me if I have missed out on anything.
    Thanks,
    Samta

    Hi,
    From wat i understood.. u have a attribute coming from BAPI.. which you want to display with two decimal places,,
    In this case.. assuming it is coming with 2 decimal places from the backend..  create a value node.. inside the node which contains the output data. set its carinality to 1..1 .. create a value attribute of type big decimal in it.. or probably string.. if there is an issue in displaying BigDecimal directly..
    map this new attribute to the necessary column in the table..
    BigDecimal value = new BigDecimal("the actual value in string or long").setScale(2);
    assign this to the value attribute created..
    (If alignment is the problem.. set the column 's textview property halign to right.. and layout as block or paragraph.. )
    Regards
    Bharathwaj
    Message was edited by:
            Bharathwaj R

  • Format to 2 decimal places?

    Hi, i need to display my data in 2 decimal places but now i'm getting results after some calculation (for eg. 2.336224). How can i round it off to 2.34?

    I also agree with Arun and Rajesh,
    When I need to specify the number of decimal points as part of an expression, e.g. ; - Tooltip series properties of a chart.
    I use; -
    =ROUND(Fields!Total.Value,2)
    or
    =FORMAT(Fields!Total.Value,"N")
    I hope this helps someone.
    If you have found any of my posts helpful then please vote them as helpful. Kieran Patrick Wood MCTS BI,MCC, PGD SoftDev (Open), MBCS http://www.innovativebusinessintelligence.com/ http://uk.linkedin.com/in/kieranpatrickwood

  • Change IDR currency with decimal place

    Dear Guru,
    Currently in my SAP env, IDR currency setting is set with 0 decimal place.(No decimal Place). However, I have user requirement to change the setting from zero to 2 decimal place. Meaning to say, to have IDR currency maintain in 2 decimal place. What is the effort and is this a big change to the system ? is this change workable ? How will this impact the existing historical data which store IDR amount with no decimal place ?
    Hope to hear from you.
    Regards
    Andrew Tay

    Dear Guru,
    Thank you for your replied. I totally agreed with you, currently my SAP system can maintain up to 15 digits with no decimal place. Beside this digits isues, is there any other areas affected ?
    Thanks in advance.
    Regards
    Andrew Tay

  • Formatting to 1 Decimal place

    Hi should be a pretty easy one but could someone help me display the Average in this line to one decimal place. I presume its done with math.round() but can't figure it out.
    Thanks in advance
    The line is:
    <c:out value="${row.Average}"/>

    or seeing as you are using JSTL
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %> 
    //or <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> for Tomcat5
    <fmt:formatNumber  value= "${row.Average}" type="number" maxFractionDigits="1" />It uses the java.text.DecimalFormat class under the hood anyway :-)
    Cheers,
    evnafets

  • Currency and decimal

    Hi,
    First, I need to know what is the max value I can go if my field type 'CURR' with length '11' and decimal '2'.
    Second, I have 2 types of field;
    DATA:  F1 LIKE ekpo-netpr,
               F2(16) TYPE p DECIMALS 5.
    If F1 = 500.00, and F2 = F1 * 1000. How the system calculates F2 since both have different length & decimals?
    Rgds,
    Haryati

    P has a length of (2n - 1), where n is the specified length.  This is different than a data domain of type CURR defined with an output length, since that length is the actual character length (although CURR is internally type P).
    If you have a data type P defined with a length of 11 and decimal 2 means:  2(11) - 1 = 21 digits (excludes the comma).  The one that is subtracted is to store the sign (+/-).  This means a max value of 9999999999999999999.99
    When you do a calculation where the decimals differ, internally the calculation uses the maximum precision, but when it is represented it will round to the specified decimal length - which is in your case 5 decimals. (eg. 32.342321 will round to 32.34232).

  • Currency and decimal points

    Hi, I have a simple spreadsheet where I'm entering dollar amounts.  I'd like to format the cells so that if I type, 1636, the result will be $16.36.  I've already got the cells set to currency, but I can't figure out how to get Numbers to auto-add the cents decimal point if I don't manually add it myself.
    It's probably pretty easy, but I've looked around the forum for answers and I can't figure this out myself.  Help is appreciated.
    Andy

    Hi Andy,
    Numbers doesn't support converting the value entered into a cell into a different value in the same cell.
    You can do the conversion in a second cell, using a formula:
    C2:  =IF(LEN(B2)>0,B2/100,"")
    Regards,
    Barry

  • OY04 setting currency maintaining (Decimal Places for currency codes) Importance

    Hello Frds,
    I have one doubt regarding OY04 setting in this we are maintaining currencies with decimals.I checked my OY04 setting some special currencies only we are maintaining in this tcode and in that  also some currencies only maintaining decimals. which type of currencies we will be maintain here.
    Which is not maintaing currencies in OY04 system is taking as per standard 2 decimals.
    For exp: INR and USD we did not maintain in OY04 setting but system is taking automatic 2 decimals.
    My question is:
    1. Which type of currencies need to be maintained in OY04.
    2. Which type of currencies need to be maintained decimals.
    3.How will we check on which program system has taking 2 decimals which is not maintained currency in OY04.
    Kindly any one can share your views about this.Thanks for your advance help.
    Regards,
    Lakshmi.

    Hi,
    the table TCURX must be already correct.
    The last time we  change it, it's when some currency disappears for EUR.
    The problem with currency, SAP save the field like if they have decimals. For example JPY, there is no decimals. You would like to save 100, SAP will save 1,00.  And when they have to write this amount, they read the table TCURX and they know the amount must be x100.
    To make it more simple, use the statement WRITE .... (INTO ...) CURRENCY my_curr  if you play with currency with decimals <> 2
    regards
    Fred

  • Legend display and decimal places

    Hi all,
    I'm using mapviewer to create thematic maps and the Ranged Bucket Advanced Style (XML below) with whole numbers but when I generate the legend each range has a ".0" on the end of it. Is there a way of turning this off?
    <?xml version="1.0" standalone="yes"?>
    <non_map_request>
    <add_style name="V.POLK THEMATIC" >
    <AdvancedStyle>
    <BucketStyle>
    <Buckets>
    <RangedBucket low="57" high="146" style="SCOTT:C.IMQ_1"/>
    <RangedBucket low="146" high="307" style="SCOTT:C.IMQ_2"/>
    <RangedBucket low="307" high="504" style="SCOTT:C.IMQ_3"/>
    <RangedBucket low="504" high="714" style="SCOTT:C.IMQ_4"/>
    <RangedBucket low="714" high="1359" style="SCOTT:C.IMQ_5"/>
    </Buckets>
    </BucketStyle>
    </AdvancedStyle>
    </add_style>
    </non_map_request>
    The legend however has these ranges :
    57.0 - 146.0
    146.0 - 307.0
    307.0 - 504.0
    504.0 - 714.0
    714.0 - 1359.0
    Any thoughts anyone? Forgive me if this has been posted before but the forum search doesn't appear to be working right now!
    Thanks
    Steve

    Hi Steve,
    at this time there is no way to turn this off.
    Joao

  • Format as 3 decimal places

    Hi All,
    i have one issue. In this QUANTITY field is there. after mapping i have to see this field with 3 decimals like for exmple
    sourc field value is   325
    but i want this value in target field like 325.000
    kindly give me answer as early as possible
    regards
    Peera

    Mahaboob,
    If your answer is yes to Paul's question, then follow the below code in UDF.
    Create simple UDF ---[ Argument : InputString]
    In Imports : java.text.DecimalFormat
        DecimalFormat threeDec = new DecimalFormat("0.000");
        threeDec.setGroupingUsed(false);
        System.out.println (threeDec.format(Double.parseDouble(InputString)));
    Hope it solves ur issues!!! If not reply back.
    Best regards,
    raj.

  • Date formatting, too many decimal places for milliseconds.

    Is there any cirmumstance where the SimpleDateFormat string of:
    "yyyy.MM.dd HH:mm:ss.SS "
    could result in some dates being output correctly with two digits for milliseconds, and others being output with three digits!

    Hi ,
    Sorry for the delay .
        x_fieldcat-scrtext_m = 'Interest Rate'.
        x_fieldcat-fieldname = 'INTEREST'.
        x_fieldcat-tabname = 'IT_BSID1'.
        x_fieldcat-col_pos = l_pos.
        x_fieldcat-outputlen = '13'.
        x_fieldcat-edit = 'X'.
        APPEND x_fieldcat TO it_fieldcat.
        CLEAR x_fieldcat.
        l_pos = l_pos + 1.
    the strcture if it_bsid1 is
    DATA : BEGIN OF IT_BSID1 OCCURS 0,
    INCLUDE STRUCTURE ZFTHUNDI_NO.
    BUKRS TYPE     BUKRS,
    HUNDI_NO  TYPE          ZHUNDI_NO,
    VBELN      TYPE      VBELN_VF,
    KDMAT      TYPE      KDMAT,
    KUNNR      TYPE     KUNNR,
    NAME1      TYPE      NAME1,
    ORT01      TYPE      ORT01,
    BUDAT      TYPE      BUDAT,
    TYPE      TYPE      ZTYPE,
    GRN_NO  TYPE     MBLNR,
    GRN_DATE  TYPE          BUDAT,
    DUEDATE      TYPE     ZDUEDATE,
    QTY      TYPE     FKIMG,
    REC_QTY TYPE     ZREC_QTY,
    ACC_QTY TYPE     ZACC_QTY,
    REJ_QTY TYPE     ZREJ_QTY,
    BAL_QTY TYPE     FKIMG,
    PRCTR     TYPE PRCTR,
    DMBTR     TYPE DMBTR,
    WRBTR     TYPE WRBTR,
    TOTAL     TYPE WRBTR,
    FAHA_NO1 TYPE     ZFAHA,
    FAHA_DATE TYPE     ZFAHA_DATE,
    HSDATE TYPE     ZHSDATE,
    HRDATE TYPE     ZHRDATE,
    DISDATE TYPE     ZDISDATE,
    HBKID     TYPE HBKID,
    INTEREST TYPE MENGE_D, ( i ve tried it with diff data types like dmbtr etc)
    W_FLAG TYPE C,
    W_FLA TYPE C ,
    LIGHT TYPE C,
    END OF IT_BSID1.

  • How to I format currency and date?

    Hi,
    I have the following code that does that:
    String price;
    String date;
    while (rs.next())
       price = rs.getString("mb_Price");
       date = rs.getString("mb_DeliveredDate");
    }price variable will display as "35.950000000000003"
    how do I format it such that it will display as "$35.95"?
    for the date value, how do I format it such that it will display "dd-mmm-yyyy"?

    Hi,
    you could use this:java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    double d = 35.26999;
    java.util.Date da = new java.util.Date();
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MMM-yyyy");
    System.out.println("$" + nf.format(d));
    System.out.println(sdf.format(da));HTH

  • Asian (JPY) currency Decimal Places Issue

    HI All,
    Need your help, we have a program which creates a BDC session and when the user tries to process it it throws an errror for amount in asian currencies like JPY - no decimal places allowed for currency, in the background it calls the FBB1 transaction.
    The original amount is in USD however after conversion when we store it back to amount field which is of type
    "glpct-tslvt"  it stores the amount in JPY currency with decimal places so for example :
    USD amount  = 93,214. 00
    JPY amount = 115,021. 86
    guess the amount is stored with decimals in BSEG table, so now when we try to process the session with the JPY amount with decimals it throws an error.
    I have tried the
    CALL FUNCTION 'CURRENCY_AMOUNT_SAP_TO_DISPLAY'
    and
    CALL FUNCTION 'BAPI_CURRENCY_GETDECIMALS'
    it gives me the correct value for amount so for above example  JPY amount = 115,021. 86 by using the mentioned two methods i am able to get the currency in this format  11502186.00 but still has two decimal places, i think it still will not work when we process the session for FBB1.
    Need your help people, appreciate your co-operation.

    sorry to revive an old thread...but we are having an issue with JPY in our electronic bank statements.
    the BAI format for our JPY account has for example 900 yen which according to our finance department is really 9 yen. the bank claims this is a known issue and the BAI format documentation seems to be confirming the bank's position in that the decimals are implied according to the currency code (whatever that means in SAP terms is a bit foggy to us).....
    currently we wrote a custom code to suppress the last two zeros (when they are zeros) but i feel this error is caused either by a wrong setting in our currency or translation tables in SAP or something else since our feeling is that this should work right out of the box without any custom programming...any ideas???...where we shoudl start looking in our currency config....does the 100:1 or 1:1 translation ratio between JPY/USD make any difference...should we try and use a function module to convert the currency ...any ideas or hints are welcome
    thanks
    Ram
    [email protected]

  • Currency Decimal places

    Hello Experts,
    I am unsing SRM 4.0 SP13 & standalone scenario.
    At present RON currency set with "No Deciamal Places" in Currency setting.  Now user wants to put 2 decimals with this currency.
    In SPRO -> SAP Web Application Server -> General Settings -> Currencies -> Set Decimal Places for Currencies,
    If i remove the RON currency,:
    1. The system will allow 2 decimal palces.
    2. Is there any impact on existing documents ( i have one docuemnt in PRD system with RON currency). If yes, how we can resolve.
    FYI: The present Decimal format is 1.234.567,89.
    Thanks in avance for your valuble inputs.
    Regards,
    Suneel Kumar.

    Hi
    RON which country boss. help others to do help very fast? romania and russia i could see..

Maybe you are looking for

  • My iphoto crashed. how do i get my pictures back?

    I was transfering photos from my nikon to iphoto when the program crashed and now it wont open my library. i restarted my computer. nothing. HELP!

  • Who's Who : does not at all show of "Placeholder" of Photo

    Dear Experts We have SAP_ESS with 600 SP16    on   SAP NW 7.00 SP20  Java System (inlcudes Application Server Java + Enterprise Portal + Enterprise Portal Core Components) When we browse thry SAP Standard " Who's Who" - It just display the employee i

  • 2 mta in the same host

    hi, i'm trying to make some test with an antivirus. i have only one server i installed ims 5.2 (smtp at port 10026) with iDS 5.2 (port 389), and i installed another iMS in the same host but the smtp is at port 25, before i install the antivirus softw

  • Location services - is this active all the time??

    I was wondering whether anyone new if location service in the iPhone 3g is constantly on in the back ground? If it is does it drain battery?? Hopefully this only starts when an app that requires it fires up.

  • Downloading ox x installation software, downloading ox x installation software

    Evidently,  the new Mac Pros don't come with an installation CD.    I am trying to install a second instance of os x on a second hard drive as a backkup and also install bootcamp to use windows. Without an installation cd, the mac is telling me to do