Formatting Negative Currency using the Java.Util Locale

Hi....
I am using the Locale file to get the currency code of a specified country. The code is given below.
public String setCurrency(String _currency){
Locale locale = new Locale("","PG");
NumberFormat format = NumberFormat.getCurrencyInstance(locale);
this.currency = format.format(Double.parseDouble(_currency));
return currency;
When i pass a negative value as the currency (-200) the string which returns will be as (PGK200) and when i pass a positive value it will be as PGK200......
How can i format this so that when i pass a negative value, the returned String will be -PGK200 ??
If there is anyone who knows how i can get this done please reply soon....
Thanks in advance.
Regards
Nuwan.

Check this out:import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
public class CurrencyEg {
    private String currency;
    public String setCurrency(String _currency){
        Locale locale = new Locale("","PG");
        //NumberFormat format = NumberFormat.getCurrencyInstance(locale);
        DecimalFormat format = (DecimalFormat)NumberFormat.getCurrencyInstance(locale);
        format.setNegativePrefix("-PKG");
        format.setNegativeSuffix("");
        format.setPositivePrefix("PKG");
        format.setPositiveSuffix("");
        format.setMaximumFractionDigits(0);
        this.currency = format.format(Double.parseDouble(_currency));
        return currency;
    public static void main(String args[]) {
        CurrencyEg eg = new CurrencyEg();
        System.out.println("200 -> " + eg.setCurrency("200"));
        System.out.println("-200 -> " + eg.setCurrency("-200"));
}I don't know how valid it is to cast and mess about with the format - but it gives exactly the output you were after:200 -> PKG200
-200 -> -PKG200

Similar Messages

  • Using the java.util.logging in JDK1.3

    I would like to use the java.util.logging classes of JDK1.4 in JDK1.3. So I tried creating a new jar with only the java.util.logging package, however, javac generates the error:
    >>>>>>
    bad class file: E:\ThinClient\Log\logging.jar(java/util/logging/Logger.class)
    class file has wrong version 48.0, should be 47.0
    Please remove or make sure it appears in the correct subdirectory of the classpath.
    <<<<<<<
    I tried placing the jar both in classpath and bootclasspath during javac and still was not successful, is there any way of getting around this, other than re-implementing this or getting some third parties implementation such as Apache's log4j?

    check out Lumberjack in sourceForge

  • Multi currency support with java.util.Locale

    My project has a requirement to support multiple currencies as our first internationalization feature. However, I've come across something with the Locale class that doesn't really make sense to me, and I'm wondering if anyone else has any best practices or insight.
    Why can't you create a Locale knowing only the ISO 3166 code? For multi-currency support, it doesn't make sense that I should need to provide a language in order to obtain a Locale, which is needed to generate the proper NumberFormat (and in 1.4 the java.util.Currency) class.
    Is there an instance where the language one speaks is directly correlated to the currency that they use?
    Actually, it doesn't make much sense that you can create a Locale only from a language either, since if my user a Hispanic-American, the language would be Spanish but the country (and therefore currency) would be US.
    It seems to me that if the Locale class can default a country code based on the language, it should also be able to default a language based on the country.
    Given these limitations, is there a recommended best practice about obtaining a Locale without a pre-determined language?

    Hi,
    this was a bit of a bugbear for a long time. Currency kind of wound up inexorably linked to Locale for a long time because the way a currency was formatted depended on the textual layout of the language as well as the country, and as date formatting was an issue too, it was easier for them to implement it the way they did.
    It's been an RFE for a long time, and I believe the beta releases of Merlin carry a currency API that is separate from a Locale. The link to the RFE is below. Hopefully Merlin Beta will allow you to achieve what you want - it seems to be pretty stable from what I've seen of it, and Sun do have a good record when it comes to releasing stable betas, so I wouldn't panic too much about the fact you're developing on a "pre-release candidate" JDK.
    http://developer.java.sun.com/developer/bugParade/bugs/4290801.html
    Hope that helps!
    Martin Hughes

  • Using the java.util.regex package

    I am trying to use the regex package to grep out portions of a string that match a regular expression. Some code from my class
        String fileList = "1_tmp.txt 2_tmp.txt 3_tmp.txt 1_inpt.txt 2_inpt.txt 3_inpt.txt 1_out.txt 2_out.txt 3_out.txt";
        String regex = "[0-9].*_out.txt"  ;
        Pattern pat = Pattern.compile(regex);
        Matcher m = pat.matcher(fileList);
        boolean succ = m.find();
        for (int i =0; i< m.groupCount(); i++) {
            System.out.println(m.group(i));
        }I was expecting to see
    1_out.txt
    2_out.txt
    3_out.txt
    This doesnt work this way, nothing gets printed out. Anybody has any idea what is wrong here?
    I am basically trying to get the same functionality as
    ls | grep "*_out.txt"
    Also is there any way to do a OR in the regular expression, like
    match [0-9]*_out.txt OR [0-9]*_out.txt
    Thanks
    -kn

    I don't see a difference in your OR, but look in the Pattern JavaDocs under logical operators.
    Second, groups are not appropriate in your situation. You have a single pattern which you wish to repeatedly find. Groups are used when you wish to pick out one subsection of a matched item. For example, a pattern dealing with a phone number might have three groups, the area code, the prefix, and the rest.
    Still, group 0 is by definition the entire matched item, so if your pattern was right, it should have worked.
    I think the critical piece is the ".*" section. * is a greedy marker and combined with the 'any chacter' marker will eat as many characters as it can. In this case, it's probably eating the rest of the string, which leaves nothing left for the "_out.txt" part of the pattern. Try using the *?, which is a reluctant marker and will basically look ahead in the pattern and eat the minimum number of characters it can.

  • Can not create WebService with java.util.Locale object why?

    I am unable to create a WebService which contains a Locale Object in the request.  I assume its because the java.util.Locale object is not Serializable.  Can anyone tell me if there is a work around for this?

    Hi,
    Make sure your strings for Locale follow these rules...
    The language string should be lower-case, two-letter codes as defined by ISO-639.
    http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt
    The country string should be upper-case, two-letter codes as defined by ISO-3166.
    http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
    Or try with some constant Locales like
    Locale.CANADA
    Locale.US
    regards,
    Uma

  • Java.util.Locale not thread-safe !

    In multithreading programming, we know that double-checking idiom is broken. But lots of code, even in sun java core libraries, are written using this idiom, like the class "java.util.Locale".
    I have submitted this bug report just now,
    but I wanted to have your opinion about this.
    Don't you think a complete review of the source code of the core libraries is necessary ?
    java.util.Locale seems not to be thread safe, as I look at the source code.
    The static method getDefault() is not synchronized.
    The code is as follows:
    public static Locale getDefault() {
    // do not synchronize this method - see 4071298
    // it's OK if more than one default locale happens to be created
    if (defaultLocale == null) {
    // ... do something ...
    defaultLocale = new Locale(language, country, variant);
    return defaultLocale;
    This method seems to have been synchronized in the past, but the bug report 4071298 removed the "synchronized" modifier.
    The problem is that for multiprocessor machines, each processor having its own cache, the data in these caches are never synchronized with the main memory.
    The lack of a memory barrier, that is provided normally by the "synchronized" modifier, can make a thread read an incompletely initialized Locale instance referenced by the static private variable "defaultlocale".
    This problem is well explained in http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html and other documents about multithreading.
    I think this method must just be synchronized again.

    Shankar, I understand that this is something books and articles about multithreading don't talk much about, because for marketing reasons, multithreading is supposed to be very simple.
    It absolutely not the case.
    Multithreading IS a most difficult topic.
    First, you must be aware that each processor has its own high-speed cache memory, much faster than the main memory.
    This cache is made of a mixture of registers and L1/L2/L3 caches.
    Suppose we have a program with a shared variable "public static int a = 0;".
    On a multiprocessor system, suppose that a thread TA running on processor P1 assign a value to this variable "a=33;".
    The write is done to the cache of P1, but not in the main memory.
    Now, a second thread TB running on processor P2 reads this variable with "System.out.prinln(a);".
    The value of "a" is retrieved from main memory, and is 0 !
    The value 33 is in the cache of P1, not in main memory where its value is still 0, because the cache of P1 has not been flushed.
    When you are using BufferedOutputStream, you use the "flush()" method to flush the buffer, and the "synch()" method to commit data to disk.
    With memory, it is the same thing.
    The java "synchronized" keyword is not only a streetlight to regulate traffic, it is also a "memory barrier".
    The opening brace "{" of a synchronized block writes the data of the processor cache into the main memory.
    Then, the cache is emptied, so that stale values of other data don't remain here.
    Inside the "synchronized" block, the thread must thus retrieve fresh values from main memory.
    At the closing brace "}", data in the processor cache is written to main memory.
    The word "synchronized" has the same meaning as the "sync()" method of FileDescriptor class, which writes data physically to disk.
    You see, it is really a cache communication problem, and the synchronized blocks allows us to devise a kind of data transfer protocol between main memory and the multiple processor local caches.
    The hardware does not do this memory reconciliation for you. You must do it yourself using "synchronized" block.
    Besides, inside a synchronized block, the processor ( or compiler ) feels free to write data in any order it feels most appropriate.
    It can thus reorder assignments and instruction.
    It is like the elevator algorithm used when you store data into a hard disk.
    Writes are reordered so that they can be retrieved more efficiently by one sweep or the magnetic head.
    This reordering, as well as the arbitrary moment the processor decides to reconciliate parts of its cache to main memory ( if you don't use synchronized ) are the source of the problem.
    A thread TB on processor P2 can retrieve a non-null pointer, and retrieve this object from main memory, where it is not yet initialized.
    It has been initialized in the cache of P1 by TA, though, but TB doen't see it.
    To summarize, use "synchronized" every time you access to shared variables.
    There is no other way to be safe.
    You get the problem, now ?
    ( Note that this problem has strictly nothing to do with the atomicity issue, but most people tend to mix the two topics...
    Besides, as each access to a shared variable must be done inside a synchronized block, the issue of atomicity is not important at all.
    Why would you care about atomicity if you can get a stale value ?
    The only case where atomicity is important is when multiple threads access a single shared variable not in synchronized block. In this case, the variable must be declared volatile, which in theory synchronizes main and cache memory, and make even long and double atomic, but as it is broken in lots of implementation, ... )

  • WS endpoints restricition: What about java.util.Locale etc.?

    We have some problems with the restrictions for WS endpoints.
    Using SAPNW Developer Studio to create a web service including the virtual interface from a stateful session bean, we are not allowed to use usual types like java.util.Locale or java.util.Properties although they are serializable.
    This is also decribed in the SAPNW DS Help:
    "The following types are not allowed anywhere in the endpoint of a Web service:
    ·        Remote objects (EJBs)
    ·        Classes extending into another class and implementing an interface
    ·        Hashed table-like types
    ·        Classes/objects that cannot be serialized"
    So what is the preferred solution for this issue?
    Is there a way to use the serializable java.util.Locale type in a WS endpoint, or do we have to use its String representation?
    What is the preferred solution for hash-table types like Properties? And what about Interface types like Map?
    Maybe we just do not find the decisive documentation link?
    Thanks a lot,
    Dirk
    Edited by: Dirk Weigand on Nov 20, 2008 8:48 AM
    Moved to "Application Server - Java Programming"

    Question moved to "Java Programming"

  • How do I create a user, in my context in OID using the Java API

    How do I create a user, with subschema, in my context in OID using the JAVA API
    I need to be able to create new users in my OID, I was doing it in our old iPlant Directory, but I don't seem to see the same methods in the Oracle LDAP API. I figured out how to get and modify the attributes of a user, but I can't seem to figure out how to add a new one.

    Try this code , modify it accordingly
    ------- cut here -------
    import oracle.ldap.util.*;
    import oracle.ldap.util.jndi.*;
    import javax.naming.NamingException;
    import javax.naming.directory.*;
    import java.io.*;
    import java.util.*;
    public class NewUser
    final static String ldapServerName = "yourLdapServer";
    final static String ldapServerPort = "4032";
    final static String rootdn = "cn=orcladmin";
    final static String rootpass = "welcome1";
    public static void main(String argv[]) throws NamingException
    // Create the connection to the ldap server
    InitialDirContext ctx = ConnectionUtil.getDefaultDirCtx(ldapServerName,
    ldapServerPort,
    rootdn,
    rootpass);
    // Create the subscriber object using the default subscriber
    Subscriber mysub = null;
    String [] mystr = null;
    try {
    RootOracleContext roc = new RootOracleContext(ctx);
    mysub = roc.getSubscriber(ctx, Util.IDTYPE_DN, "o=dec", mystr);
    catch (UtilException e) {
    e.printStackTrace();
    // Create ModPropertySet with user information
    ModPropertySet mps = new ModPropertySet();
    mps.addProperty(LDIF.ATTRIBUTE_CHANGE_TYPE_ADD,"cn", "Steve.Harvey");
    mps.addProperty(LDIF.ATTRIBUTE_CHANGE_TYPE_ADD,"sn", "Harvey");
    mps.addProperty(LDIF.ATTRIBUTE_CHANGE_TYPE_ADD,"uid", "SHarvey");
    mps.addProperty(LDIF.ATTRIBUTE_CHANGE_TYPE_ADD,"givenname", "Steve");
    mps.addProperty(LDIF.ATTRIBUTE_CHANGE_TYPE_ADD,"mail", "[email protected]");
    mps.addProperty(LDIF.ATTRIBUTE_CHANGE_TYPE_ADD,"userpassword", "welcome1");
    // Create the user
    User newUser = null;
    try {
    newUser = mysub.createUser(ctx, mps, true);
    System.out.println("New User DN: " + newUser.getDN(ctx));
    catch (UtilException e) {
    e.printStacktrace();
    ------- end cut --------
    Enjoy.
    Suhail

  • Help needed in using the DocCheck utility

    Hi
    Can somebody help me to use the DocCheck utility.I need to check that all the java files have the required javadoc tags and they are correct.
    I have downloaded the zip file and I have been giving the following commands
    c:\javadoc -doclet com.sun.tools.doclets.doccheck.DocCheck -docletpath c:\svk\jdk1.2.2\bin\doccheck1.2b1\lib\doccheck.jar -sourcepath<full path with the file name>
    But I get the following error message : No package or class specified.
    I also tried giving the following command:
    D:\SegaSource\sega\src\com\sega\account>javadoc -doclet com.sun.tools.doclets.do
    ccheck.DocCheck -docletpath d:\jdk1.3\doccheck1.2b1\lib\doccheck.jar User.java
    But I get the following message:
    Loading source file User.java...
    Constructing Javadoc information...
    javadoc: warning - Import not found: com.sega.account.address.Address - ignoring
    javadoc: warning - Import not found: com.sega.account.icon.Icon - ignoring!
    javadoc: warning - Import not found: com.sega.common.DateUtil - ignoring!
    javadoc: warning - Import not found: atg.nucleus.GenericService - ignoring!
    javadoc: warning - Cannot find class com.sega.account.icon.Icon
    javadoc: warning - Cannot find class com.sega.account.address.Address
    javadoc: warning - Cannot find class com.sega.account.MasterManager
    7 warnings
    please help
    Thanks
    SVK

    I have never ran the DocCheck from the command prompt, so I really don't know how to do it, but I do run it succesfully using ant (build tool from apache - jakarta, if you use tomcat you already have it installed).
    So.. if you do use ant.. this will help:
    <target name="doccheck" depends="prepare">
         <javadoc
              packagenames="${packages}"
                    destdir="${doccheck.home}"
              doclet="com.sun.tools.doclets.doccheck.DocCheck"
              docletpath="${doccheck.path}" >
              <classpath refid="project.classpath"/>
              <sourcepath refid="project.classpath"/>
         </javadoc>
    </target>If you don't use it.. I guess I was of no help, sorry.
    Ylan

  • I am trying to upgrade my hard drive in my mac book pro using the disk utility in an attempt to clone my old hard drive.  I can only get so far, just before cloning may start and receive an "error 254" and can go no further.  Any idea what this error is?

    I am trying to upgrad the hard drive in my mac book pro using the disk utility in an attempt to clone my old hard drive.  I can only get so far throughj the process where its about to start cloing when I get a message " error 254".  Any idea what that means and how do I get around this issue so I can use my new hard drive?  Thanks for your input.
    Vince

    Connect the HDD to your MBP.  Open Disk Utility>Erase and drag the HDD icon inrt the Name field.  The format should be Mac OS Extended (Journaled).  Click on the Erase button.
    Then try the clone process again.  You may use Disk Utility>Restore or a third party cloning application such as Carbon Copy Cloner or Super Duper.
    Ciao.

  • Get days from the java.util.date class

    Does anyone know how to get the days from the java.util.date
    class. I'm trying to subtract two dates to get the total days between
    the two dates. Any help would be appriciated
    Rob

    If you use the getTime() method, you get the date as a number of milliseconds since a predefined time. You can do arithmetic on that number, such as subtracting two of them to get the number of milliseconds between two Dates, and so on.

  • How to use the Java embedding activity in BPel

    hi all,
    How to use the java embedding activity in BPEL
    pls can u provide sample example

    1 Use [Oracle BPEL Process Manager Client Java API Reference|http://download-uk.oracle.com/docs/cd/B31017_01/integrate.1013/b28986/overview-summary.html] and especially [com.collaxa.cube.engine.ext|http://download-uk.oracle.com/docs/cd/B31017_01/integrate.1013/b28986/com/collaxa/cube/engine/ext/BaseBPELXExecLet.html]
    Instead of System.Out.println use addAuditTrailEntry(java.lang.String message)
    2. If you want to import a package write in code (Source View) of bpel process
    +<bpelx:exec import="package_name"/>+ for example +<bpelx:exec import="java.util.regex.Matcher"/>+
    example 1:
    String bodyAsString;
    StringBuffer myStringBuffer = new StringBuffer();
    try {
    bodyAsString = (String)getVariableData("BodyString");
    addAuditTrailEntry("bodyAsString1: "+ bodyAsString);
    Pattern pattern = Pattern.compile("goodDay");
    Matcher matcher= pattern.matcher(bodyAsString);
    while (matcher.find()) {   
    matcher.appendReplacement(myStringBuffer, "shitDay");
    matcher.appendTail(myStringBuffer);
    bodyAsString = myStringBuffer.toString();
    addAuditTrailEntry("bodyAsString2: "+ bodyAsString);
    } catch (Exception ex) {
    addAuditTrailEntry("Failed+bodyAsString",ex.getMessage());
    I put in code (Source View) the following
    <bpelx:exec import="java.util.regex.Matcher"/>
    <bpelx:exec import="java.util.regex.Pattern"/>
    example2:
    Object temp;
    try {
    temp = ((XMLElement)getVariableData("inputVariable","payload","/ns2:FiscalisMessage/ns2:Body")).getChildNodes().item(1);
    setVariableData("AdjReceipt",temp);
    addAuditTrailEntry("ok",temp.toString());
    catch (Exception ex) {
    addAuditTrailEntry("Failed :",ex);
    I put in code (Source View) the following
    <bpelx:exec import="oracle.xml.parser.v2.XMLElement"/>

  • Using the JAVA ImportXmlTemplate function, should I always use XSL directory?

    Using the JAVA ImportXmlTemplate function requires XSL directory, I do not need XSL for my updates, how can I workaround this requirement?

    Ok, thanks for your quick answer. I saw you last blog posting regarding simple bar codes, I hope your next one turns up soon (read: today ;-) ).
    I did take a swing at writing my own class according to the user guide, using JDeveloper. One of my problems is that I am not that familiar with the whole java world, my experience lies almost entirely within .NET development. So when I read stuff like "make sure the class is available in the classpath for the JVM" and things like that, it is not a detailed enough description for me in order to make anything out of it. Do you think you can clarify that for me?
    I also wonder if you have any tips and tricks on how to trace/log information from the class when it executes? Because I think that I can actually get it to be called, it's just that something goes wrong and the generated PDF becomes badly formatted and has no content. I can see that some calls are made to a Logger class inside the example class. I guess that I need to set up some runtime configuration for that information to turn up in a file, but again me lacking experience from the java world prevents me from accomplishing that :-)
    Regarding tracing and logging from the java classes for the BI Publisher, can I get them to trace or log debug information in some clever way?
    The app I am developing is a .NET app that calls these classes using a product called juggerNET. I am developing a print direct application for JDEdwards EnterpriseOne since BI Publisher is not entirely integrated into it yet.
    I would greatly appreciate a quick reply this time as well if you can find the time!
    Best regards, Jörgen

  • Using the Java API

    Hi everyone,
    I just wanted to see if anyone knows whether I need a license to use the Java API included in the trial version of Adobe LiveCycle ES.
    I need to include some PDF manipulation code for dynamic XFA forms in an application, and I first read that XPAAJ jar was free. So is the API here also free or do I need a license? If anyone knows, could you please point me in the direction of the details if a license is needed.
    I would appreciate your help.
    Thanks.
    Mira.

    Mira
    You don't need a license as long as the application you're building is for evaluation or testing, and NOT for production use.
    You will need to purchase a license for production use.
    Licensing can be complex, and you should contact your local Adobe office or enterprise partner for details.
    XPAAJ was never free, it was bundled with other Adobe products.
    It has been deprecated, and is no longer supplied or supported, as far as I'm aware. You will need to purchase a LiveCycle license of some sort.
    Howard
    http://www.avoka.com

  • Would using a Apple Time Capsules be easier to use as you can use the Airport Utility to set everything up? Would using encryption affect the speed / durability / life span of the drive in a computer or Time Capsule?

    Would using a Apple Time Capsules be easier to use as you can use the Airport Utility to set everything up?
    OR would there be better programs out there that would do more than Airport Utility on a non Apple drive?
    Would using encryption affect the speed / durability / life span of the drive / Fusion drive in a computer or Time Capsule?

    1. Time Capsules are the easiest device to setup for Time Machine.
    2. Sorry this is unclear. There are a huge number of routers available that have far superior controls than apple routers.. some support Time Machine.. most don't. They negate your question 1. in being difficult to setup. And alot of 3rd party devices that claim Time Machine compatibility are unreliable.
    3. Encryption is irrelevant.

Maybe you are looking for