1

I need to learn how to convert a long value into a currency formatted string in a toString() method with the following scenarios:

  • If given long value = 9287, needs to be displayed as $92.87
  • If given long value = -9287, needs to be displayed as $-92.87
  • If given long value = 100000000, needs to be displayed as $1,000,000.00
  • If given long value = 49, needs to be displayed as $0.49

Any help from string gurus is appreciated.

4

3 に答える 3

1
public static void main(String [] args){

       DecimalFormat f = new DecimalFormat("$#,##0.00;-$#,##0.00");

       //test with
       long num1 = 9287;
       long num2 = -9287;
       long num3 = 100000000;
       long num4 = 49;

       System.out.println("num1 = "+f.format(num1/100.0));
       System.out.println("num2 = "+f.format(num2/100.0));
       System.out.println("num3 = "+f.format(num3/100.0));
       System.out.println("num4 = "+f.format(num4/100.0));
}
于 2012-10-12T19:59:10.713 に答える
0

I hope you're using Java. Try this :

            import java.text.NumberFormat;

            NumberFormat f = NumberFormat.getCurrencyInstance();
            System.out.println(f.format(doubleValue(yourVar)/100));
于 2012-10-12T16:16:28.860 に答える
0

String.format() does not support currency format. So you need to insert currency symbol yourself or use java.text package.

package tests;

import java.util.Locale;

public class App201210130101 {

/**
 * @param args
 */
public static void main(String[] args) {
    long value;

    value = 9287;
    print(value);

    value = -9287;
    print(value);

    value = 100000000;
    print(value);

    value = 49;
    print(value);
}

public static void print(long value) {

    System.out.println(String.format(Locale.US, "$%,.2f", (double)value/100));
}

}
于 2012-10-12T21:11:34.333 に答える