How to use String.format to convert a long to a String in currency format in Java
-
07-07-2021 - |
質問
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.
解決
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));
}
他のヒント
I hope you're using Java. Try this :
import java.text.NumberFormat;
NumberFormat f = NumberFormat.getCurrencyInstance();
System.out.println(f.format(doubleValue(yourVar)/100));
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));
}
}
所属していません StackOverflow