태그 보관물: number-formatting

number-formatting

자바 통화 번호 형식 지정하는 방법이 있습니까? 100

다음과 같이 십진수 형식을 지정하는 방법이 있습니까?

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);
    }
}

답변

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);
    }
}

답변

예. java.util.formatter 를 사용할 수 있습니다 . “% 10.2f”와 같은 형식화 문자열을 사용할 수 있습니다.


답변

나는 이것을 사용하고 있습니다 (commons-lang의 StringUtils 사용).

Double qty = 1.01;
String res = String.format(Locale.GERMANY, "%.2f", qty);
String fmt = StringUtils.removeEnd(res, ",00");

절단 할 로케일 및 해당 문자열 만 관리해야합니다.


답변

나는 이것이 통화를 인쇄하는 데 간단하고 명확하다고 생각합니다.

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