문제

Java에서 숫자 형식을 어떻게 지정합니까?
"모범 사례"는 무엇입니까?

숫자를 포맷하기 전에 반올림해야 합니까?

32.302342342342343 => 32.30

.7323 => 0.73

등.

도움이 되었습니까?

해결책

에서 이 스레드, 이를 수행하는 방법에는 여러 가지가 있습니다.

double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12

f = (float) (Math.round(n*100.0f)/100.0f);

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

// The value of dd2dec will be 100.24

그만큼 십진수 형식() 가장 역동적인 방법인 것 같고, 다른 코드를 읽을 때 이해하기도 매우 쉽습니다.

다른 팁

당신과 String.format() 새로운 가장 친한 친구가 될 것입니다!

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax

 String.format("%.2f", (double)value);

NumberFormat(및 대부분의 다른 Format 하위 항목)의 자손 클래스는 동기화되지 않습니다.형식 개체를 생성하고 이를 util 클래스의 정적 변수에 저장하는 것은 일반적인(그러나 위험한) 관행입니다.실제로는 상당한 부하가 발생하기 시작할 때까지 거의 항상 작동합니다.

예, 둥근 숫자입니다.이것이 주요 예제 소스.

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 


import java.util.*;
import java.text.*;

public class DecimalFormatDemo {

    static public void customFormat(String pattern, double value ) {
        DecimalFormat myFormatter = new DecimalFormat(pattern);
        String output = myFormatter.format(value);
        System.out.println(value + "  " + pattern + "  " + output);
    }

    static public void localizedFormat(String pattern, double value,                                       Locale loc ) {
        NumberFormat nf = NumberFormat.getNumberInstance(loc);
        DecimalFormat df = (DecimalFormat)nf;
        df.applyPattern(pattern);
        String output = df.format(value);
        System.out.println(pattern + "  " + output + "  " + loc.toString());
    }

    static public void main(String[] args) {

        customFormat("###,###.###", 123456.789);
        customFormat("###.##", 123456.789);
        customFormat("000000.000", 123.78);
        customFormat("$###,###.###", 12345.67);
        customFormat("\u00a5###,###.###", 12345.67);

        Locale currentLocale = new Locale("en", "US");

        DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);
        unusualSymbols.setDecimalSeparator('|');
        unusualSymbols.setGroupingSeparator('^');
        String strange = "#,##0.###";
        DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);
        weirdFormatter.setGroupingSize(4);
        String bizarre = weirdFormatter.format(12345.678);
        System.out.println(bizarre);

        Locale[] locales = {
            new Locale("en", "US"),
            new Locale("de", "DE"),
            new Locale("fr", "FR")
        };

        for (int i = 0; i < locales.length; i++) {
            localizedFormat("###,###.###", 123456.789, locales[i]);
        }
     }
 }

이 시도:

String.format("%.2f", 32.302342342342343);

간단하고 효율적입니다.

표준 라이브러리에는 두 가지 접근 방식이 있습니다.하나는 java.text.DecimalFormat을 사용하는 것입니다.java.util.Formatter를 기반으로 하는 다른 좀 더 비밀스러운 메소드(String.format, PrintStream.printf 등)는 C 프로그래머를 행복하게 해줄 것입니다.

Robert가 그의 대답에서 지적했듯이:DecimalFormat은 동기화되지 않으며 API도 스레드 안전성을 보장하지 않습니다(사용 중인 JVM 버전/공급업체에 따라 달라질 수 있음).

스프링을 사용하세요 숫자 포맷터 대신 스레드로부터 안전합니다.

public static void formatDouble(double myDouble){
 NumberFormat numberFormatter = new DecimalFormat("##.000");
 String result = numberFormatter.format(myDouble);
 System.out.println(result);
}

예를 들어, 이중 값이 FormatDouble () 메소드로 전달 된 경우 다음과 같은 결과가됩니다.345.937 마찬가지로, .7697 값이 메소드로 전달되면 다음이 결과가 될 것입니다..770

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top