programing

통화 형식으로 소수점 형식을 지정하려면 어떻게 해야 합니까?

javaba 2022. 10. 6. 21:20
반응형

통화 형식으로 소수점 형식을 지정하려면 어떻게 해야 합니까?

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

100   -> "100"  
100.1 -> "100.10"

동그라미 숫자일 경우 소수점을 생략합니다.그렇지 않으면 소수점 두 자리로 포맷합니다.

java.text 패키지를 사용할 것을 권장합니다.

double money = 100.1;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String moneyString = formatter.format(money);
System.out.println(moneyString);

이것에 의해, 로케일 고유의 메리트가 추가됩니다.

단, 필요한 경우 반환된 문자열이 1달러일 경우 잘라냅니다.

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

이것도 사용할 수 있습니다(thous separator와 함께).

double amount = 2000000;    
System.out.println(String.format("%,.2f", amount));          

2,000,000.00

글쎄요.문제는 플로트일 경우 100은 절대 100이 아니라는 것입니다.보통 99.9999999 또는 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
  }
}

구글 검색 후 좋은 해결책을 찾지 못했기 때문에 다른 사람이 참고할 수 있도록 제 해결책을 올려주세요.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);
    }
}
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

이것을 사용하고 있습니다(commons-lang의 String Utils 사용).

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

절단할 로케일과 대응하는 문자열만 관리해야 합니다.

가장 좋은 방법이라고 생각합니다.

    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'

다음과 같은 작업을 수행해야 합니다.

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

통화 인쇄는 간단하고 명확하다고 생각합니다.

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 필드가 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));

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

오래된 질문인 건 알지만...

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

@@duffymo를 데 합니다.java.text.NumberFormat방법을 찾아야 합니다.실제로 String을 직접 비교하지 않고 모든 포맷을 네이티브로 실행할 수 있습니다.

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단지 2루타/2루타의 부정확성에 대처하고 있을 뿐입니다.기본적으로 우리가 수백 개의 자리를 반올림했는지 확인하는 것(아마 이것은 미국의 편견일 것이다)만 해도 남는 센트가 있다.
  • 소수점을 제거하는 방법은setMaximumFractionDigits()방법

소수점 이하를 잘라낼지 말지를 결정하는 논리가 무엇이든 간에setMaximumFractionDigits()사용되어야 합니다.

10000.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;
}

통화에 대해 작업하려면 Big Decimal 클래스를 사용해야 합니다.문제는 몇 가지 플로트 번호를 메모리에 저장할 방법이 없다는 것입니다(예:5.3456은 저장할 수 있지만 5.3455는 저장할 수 없으므로 계산이 잘못될 수 있습니다.

Big Decimal 및 통화와 협력하는 좋은 기사가 있습니다.

http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html

이 게시물은 제가 원하는 것을 얻는데 큰 도움이 되었습니다.그래서 다른 사람들을 돕기 위해 제 코드를 여기에 쓰고 싶었어요.여기 제 코드와 몇 가지 설명이 있습니다.

다음 코드:

double moneyWithDecimals = 5.50;
double moneyNoDecimals = 5.00;
System.out.println(jeroensFormat(moneyWithDecimals));
System.out.println(jeroensFormat(moneyNoDecimals));

반환:

€ 5,-
€ 5,50

실제 zeroensFormat() 메서드는 다음과 같습니다.

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

메서드를 호출하는 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 ,-)

이 코드는 현재 통화를 사용합니다.제 경우는 네덜란드이기 때문에 포맷된 문자열은 미국에 있는 스트링과는 다릅니다.

  • 네덜란드: 999.999,999
  • 미국: 999,999.99

이 숫자들의 마지막 세 글자를 보세요.내 코드에는 마지막 3자가 ",00"과 동일한지 확인하는 if 문이 있습니다.미국에서 사용하려면 아직 작동하지 않으면 ".00"으로 변경해야 할 수 있습니다.

통화를 포맷하고 싶지만 로컬을 기반으로 하고 싶지 않은 사용자에게는 다음과 같은 작업을 수행할 수 있습니다.

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

그 대신 정수를 사용하여 금액을 센트로 나타냅니다.

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달러보다 더 좋아보여요

더 나은 방법을 찾는 사람이 있을 경우 Number를 사용하십시오.형식, 귀 기울여 듣겠습니다.

난 내 기능을 쓸 만큼 미쳤지

정수를 통화 형식으로 변환합니다(소수에 대해서도 수정할 수 있습니다).

 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);
    }
double amount = 200.0;

NumberFormat Us = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(Us.format(amount));

출력:
$200.00

언급URL : https://stackoverflow.com/questions/2379221/how-to-format-decimals-in-a-currency-format

반응형