Reputation: 25
I need to learn how to convert a long
value into a currency formatted string in a toString()
method with the following scenarios:
Any help from string gurus is appreciated.
Upvotes: 1
Views: 897
Reputation: 30127
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));
}
}
Upvotes: 0
Reputation: 7996
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));
}
Upvotes: 1
Reputation: 2399
I hope you're using Java. Try this :
import java.text.NumberFormat;
NumberFormat f = NumberFormat.getCurrencyInstance();
System.out.println(f.format(doubleValue(yourVar)/100));
Upvotes: 0