다음과 같이 십진수 형식을 지정하는 방법이 있습니까?
100 -> "100"
100.1 -> "100.10"
반올림 숫자 인 경우 소수 부분을 생략하십시오. 그렇지 않으면 소수점 이하 두 자리로 형식을 지정하십시오.
답변:
나는 그것을 의심한다. 문제는 100이 float이면 100이 아니라, 일반적으로 99.9999999999 또는 100.0000001 또는 이와 비슷한 것입니다.
그런 식으로 서식을 지정하려면 엡실론, 즉 정수로부터의 최대 거리를 정의하고 차이가 더 작 으면 정수 서식을 사용하고 그렇지 않으면 부동 소수점을 사용해야합니다.
이와 같은 것이 트릭을 수행합니다.
public String formatDecimal(float number) {
float epsilon = 0.004f; // 4 tenths of a cent
if (Math.abs(Math.round(number) - number) < epsilon) {
return String.format("%10.0f", number); // sdb
} else {
return String.format("%10.2f", number); // dj_segfault
}
}
java.text 패키지를 사용하는 것이 좋습니다.
double money = 100.1;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String moneyString = formatter.format(money);
System.out.println(moneyString);
이것은 특정 로케일이라는 추가 이점이 있습니다.
그러나 필요한 경우 전체 달러 인 경우 반환되는 문자열을 자릅니다.
if (moneyString.endsWith(".00")) {
int centsIndex = moneyString.lastIndexOf(".00");
if (centsIndex != -1) {
moneyString = moneyString.substring(1, centsIndex);
}
}
BigDecimal포맷터와 함께 사용하십시오 . joda-money.sourceforge.net 은 일단 완료되면 사용하기에 좋은 라이브러리 여야합니다.
double amount =200.0;
Locale locale = new Locale("en", "US");
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
System.out.println(currencyFormatter.format(amount));
또는
double amount =200.0;
System.out.println(NumberFormat.getCurrencyInstance(new Locale("en", "US"))
.format(amount));
통화를 표시하는 가장 좋은 방법
산출
$ 200.00
기호를 사용하지 않으려면이 방법을 사용하십시오.
double amount = 200;
DecimalFormat twoPlaces = new DecimalFormat("0.00");
System.out.println(twoPlaces.format(amount));
200.00
이것은 또한 사용할 수 있습니다 (천 단위 구분 기호 사용)
double amount = 2000000;
System.out.println(String.format("%,.2f", amount));
2,000,000.00
Google 검색 후 좋은 해결책을 찾지 못했습니다. 다른 사람이 참조 할 수 있도록 내 솔루션을 게시하십시오. priceToString 을 사용 하여 돈을 형식화하십시오.
public static String priceWithDecimal (Double price) {
DecimalFormat formatter = new DecimalFormat("###,###,###.00");
return formatter.format(price);
}
public static String priceWithoutDecimal (Double price) {
DecimalFormat formatter = new DecimalFormat("###,###,###.##");
return formatter.format(price);
}
public static String priceToString(Double price) {
String toShow = priceWithoutDecimal(price);
if (toShow.indexOf(".") > 0) {
return priceWithDecimal(price);
} else {
return priceWithoutDecimal(price);
}
}
"###,###,###.00""###,###,##0.00"
예. java.util.formatter 를 사용할 수 있습니다 . "% 10.2f"와 같은 형식화 문자열을 사용할 수 있습니다.
String.format()이를위한 멋진 정적 래퍼입니다. 그래도 왜 '10'을 사용하는지 모르겠습니다.
나는 이것이 통화를 인쇄하는 데 간단하고 명확하다고 생각합니다.
DecimalFormat df = new DecimalFormat("$###,###.##"); // or pattern "###,###.##$"
System.out.println(df.format(12345.678));
산출량 : $ 12,345.68
질문에 대한 가능한 해결책 중 하나 :
public static void twoDecimalsOrOmit(double d) {
System.out.println(new DecimalFormat(d%1 == 0 ? "###.##" : "###.00").format(d));
}
twoDecimalsOrOmit((double) 100);
twoDecimalsOrOmit(100.1);
산출:
100
100.10
json money field가 float이면 3.1, 3.15 또는 3으로 올 수 있습니다.
이 경우 적절한 표시를 위해 반올림해야 할 수 있습니다 (그리고 나중에 입력 필드에 마스크를 사용할 수 있도록 함).
floatvalue = 200.0; // it may be 200, 200.3 or 200.37, BigDecimal will take care
Locale locale = new Locale("en", "US");
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
BigDecimal valueAsBD = BigDecimal.valueOf(value);
valueAsBD.setScale(2, BigDecimal.ROUND_HALF_UP); // add digits to match .00 pattern
System.out.println(currencyFormatter.format(amount));
그렇게하는 가장 좋은 방법입니다.
public static String formatCurrency(String amount) {
DecimalFormat formatter = new DecimalFormat("###,###,##0.00");
return formatter.format(Double.parseDouble(amount));
}
100-> "100.00
"100.1-> "100.10"
NumberFormat currency = NumberFormat.getCurrencyInstance();
String myCurrency = currency.format(123.5);
System.out.println(myCurrency);
산출:
$123.50
통화를 변경하려면
NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.CHINA);
String myCurrency = currency.format(123.5);
System.out.println(myCurrency);
산출:
¥123.50
다음과 같이해야합니다.
public static void main(String[] args) {
double d1 = 100d;
double d2 = 100.1d;
print(d1);
print(d2);
}
private static void print(double d) {
String s = null;
if (Math.round(d) != d) {
s = String.format("%.2f", d);
} else {
s = String.format("%.0f", d);
}
System.out.println(s);
}
인쇄 :
100
100,10
나는 이것이 오래된 질문이라는 것을 알고 있지만 ...
import java.text.*;
public class FormatCurrency
{
public static void main(String[] args)
{
double price = 123.4567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(price));
}
}
이런 식으로 정수를 전달한 다음 센트를 전달할 수 있습니다.
String.format("$%,d.%02d",wholeNum,change);
java.text.NumberFormat이런 종류의 방법 을 사용해야한다는 @duffymo에 동의합니다 . 실제로 문자열 비교를 수행하지 않고도 기본적으로 모든 형식을 지정할 수 있습니다.
private String formatPrice(final double priceAsDouble)
{
NumberFormat formatter = NumberFormat.getCurrencyInstance();
if (Math.round(priceAsDouble * 100) % 100 == 0) {
formatter.setMaximumFractionDigits(0);
}
return formatter.format(priceAsDouble);
}
지적해야 할 몇 가지 사항 :
Math.round(priceAsDouble * 100) % 100 가 복식 / 수로의 부정확성을 해결하고 있습니다. 기본적으로 우리가 수백 위까지 반올림하는지 (아마 이것은 미국 편향 일 수도 있음) 나머지 센트가 있는지 확인하는 것입니다. setMaximumFractionDigits()방법은소수점을자를 지 여부를 결정하는 논리가 무엇이든 setMaximumFractionDigits()사용해야합니다.
*100와 %100미국 바이어스되고, 당신이 사용할 수있는 Math.pow(10, formatter.getMaximumFractionDigits())대신에 하드 코딩의 100로케일에 대한 올바른 번호를 사용 ...
통화 작업을하려면 BigDecimal 클래스를 사용해야합니다. 문제는 일부 부동 숫자를 메모리에 저장할 방법이 없다는 것입니다 (예 : 5.3456을 저장할 수 있지만 5.3455는 저장할 수 없음). 이는 잘못된 계산에 영향을 미칠 수 있습니다.
BigDecimal 및 통화와 협력하는 방법에 대한 멋진 기사가 있습니다.
http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html
1000000.2에서 1,000,000,20까지 형식
private static final DecimalFormat DF = new DecimalFormat();
public static String toCurrency(Double d) {
if (d == null || "".equals(d) || "NaN".equals(d)) {
return " - ";
}
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
DecimalFormatSymbols symbols = DF.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
String ret = DF.format(bd) + "";
if (ret.indexOf(",") == -1) {
ret += ",00";
}
if (ret.split(",")[1].length() != 2) {
ret += "0";
}
return ret;
}
이 게시물은 내가 원하는 것을 마침내 얻는 데 정말로 도움이되었습니다. 그래서 나는 다른 사람들을 돕기 위해 여기에 내 코드를 기여하고 싶었습니다. 여기에 몇 가지 설명이있는 코드가 있습니다.
다음 코드 :
double moneyWithDecimals = 5.50;
double moneyNoDecimals = 5.00;
System.out.println(jeroensFormat(moneyWithDecimals));
System.out.println(jeroensFormat(moneyNoDecimals));
반환 :
€ 5,-
€ 5,50
실제 jeroensFormat () 메서드 :
public String jeroensFormat(double money)//Wants to receive value of type double
{
NumberFormat dutchFormat = NumberFormat.getCurrencyInstance();
money = money;
String twoDecimals = dutchFormat.format(money); //Format to string
if(tweeDecimalen.matches(".*[.]...[,]00$")){
String zeroDecimals = twoDecimals.substring(0, twoDecimals.length() -3);
return zeroDecimals;
}
if(twoDecimals.endsWith(",00")){
String zeroDecimals = String.format("€ %.0f,-", money);
return zeroDecimals; //Return with ,00 replaced to ,-
}
else{ //If endsWith != ,00 the actual twoDecimals string can be returned
return twoDecimals;
}
}
jeroensFormat () 메소드를 호출하는 displayJeroensFormat 메소드
public void displayJeroensFormat()//@parameter double:
{
System.out.println(jeroensFormat(10.5)); //Example for two decimals
System.out.println(jeroensFormat(10.95)); //Example for two decimals
System.out.println(jeroensFormat(10.00)); //Example for zero decimals
System.out.println(jeroensFormat(100.000)); //Example for zero decimals
}
다음과 같은 출력이 있습니다.
€ 10,50
€ 10,95
€ 10,-
€ 100.000 (In Holland numbers bigger than € 999,- and wit no decimals don't have ,-)
이 코드는 현재 통화를 사용합니다. 제 경우에는 네덜란드이므로 형식화 된 문자열이 미국에있는 사람과 다를 것입니다.
그 숫자의 마지막 3 자만보십시오. 내 코드에는 마지막 3 개의 문자가 ", 00"과 같은지 확인하는 if 문이 있습니다. 미국에서 사용하려면 아직 작동하지 않는 경우 ".00"으로 변경해야 할 수 있습니다.
나는 내 자신의 함수를 작성하기에 충분히 미쳤다.
이렇게하면 정수를 통화 형식으로 변환합니다 (소수점에서도 수정할 수 있음).
String getCurrencyFormat(int v){
String toReturn = "";
String s = String.valueOf(v);
int length = s.length();
for(int i = length; i >0 ; --i){
toReturn += s.charAt(i - 1);
if((i - length - 1) % 3 == 0 && i != 1) toReturn += ',';
}
return "$" + new StringBuilder(toReturn).reverse().toString();
}
public static String formatPrice(double value) {
DecimalFormat formatter;
if (value<=99999)
formatter = new DecimalFormat("###,###,##0.00");
else
formatter = new DecimalFormat("#,##,##,###.00");
return formatter.format(value);
}
대신 정수를 사용하여 금액을 센트로 표시했습니다.
public static String format(int moneyInCents) {
String format;
Number value;
if (moneyInCents % 100 == 0) {
format = "%d";
value = moneyInCents / 100;
} else {
format = "%.2f";
value = moneyInCents / 100.0;
}
return String.format(Locale.US, format, value);
}
문제 NumberFormat.getCurrencyInstance()는 때때로 $ 20이 $ 20이되기를 원한다는 것입니다. $ 20.00보다 낫습니다.
누군가 NumberFormat을 사용하여 더 나은 방법을 찾으면 모두 귀를 기울입니다.
통화 형식을 지정하고 싶지만 현지 통화를 기반으로하지 않으려는 사람들을 위해 다음과 같이 할 수 있습니다.
val numberFormat = NumberFormat.getCurrencyInstance() // Default local currency
val currency = Currency.getInstance("USD") // This make the format not locale specific
numberFormat.setCurrency(currency)
...use the formator as you want...