Program Club

자바 통화 번호 형식

proclub 2020. 10. 10. 12:30
반응형

자바 통화 번호 형식


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

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


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 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()사용해야합니다.


그렇게하는 가장 좋은 방법입니다.

    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"


통화 작업을하려면 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 ,-)

This code uses your current currency. In my case that's Holland so the formatted string for me will be different than for someone in the US.

  • Holland: 999.999,99
  • US: 999,999.99

Just watch the last 3 characters of those numbers. My code has an if statement to check if the last 3 characters are equal to ",00". To use this in the US you might have to change that to ".00" if it doesn't work already.


I was crazy enough to write my own function:

This will convert integer to currency format (can be modified for decimals as well):

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

This is what I did, using an integer to represent the amount as cents instead:

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

The problem with NumberFormat.getCurrencyInstance() is that sometimes you really want $20 to be $20, it just looks better than $20.00.

If anyone finds a better way of doing this, using NumberFormat, I'm all ears.


For the people who wants to format the currency, but does not want it to be based on local, we can do this:

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...

참고URL : https://stackoverflow.com/questions/2379221/java-currency-number-format

반응형