programing

Java에서 숫자 형식을 지정하려면 어떻게 해야 합니까?

randomtip 2022. 11. 21. 22:35
반응형

Java에서 숫자 형식을 지정하려면 어떻게 해야 합니까?

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

Decimal Format()이 가장 역동적인 방법인 것 같습니다.또, 다른 코드를 읽을 때도 알기 쉽습니다.

당신과String.format()새로운 베스트 프렌드가 될 거야!

https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

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

Number에서 하강하는 클래스는형식(및 대부분의 다른 형식 하위 형식)은 동기화되지 않습니다.형식 객체를 생성하여 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);

심플하고 효율적입니다.

Decimal Format을 사용합니다.

표준 라이브러리에는 두 가지 접근 방식이 있습니다.하나는 java.text를 사용하는 것입니다.Decimal Format(십진수 형식)다른 암호 방식(String).포맷, PrintStream.printf 등)을 java.util에 기반합니다.포메터는 C 프로그래머를 행복하게 유지해야 합니다.

로버트가 답변에서 지적한 바와 같이:DecimalFormat은 동기화되지 않으며 API는 스레드의 안전을 보장하지 않습니다(사용하는 JVM 버전/벤더에 따라 다를 수 있습니다).

대신 스레드 세이프인 스프링의 Number formatter를 사용하십시오.

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

예를 들어 formatDouble() 메서드에 전달된 더블 값이 345.9372인 경우 마찬가지로 값 .7697이 메서드에 전달되면 다음과 같은 결과가 됩니다..770

언급URL : https://stackoverflow.com/questions/50532/how-do-i-format-a-number-in-java

반응형