2016-09-01 3 views
3

나는 그것이 분수가있는 경우 소수점 이하 2 곳을 정확한하는 이중의 형식을, 그렇지 않으면 지금에 DecimalFormat형식, 자바

를 사용하여 차단하는 것을 시도하고있는 정수를 2 개 진수의 두 배를위한 장소와 0, 내가 좋아하는 것

100.123 -> 100.12 
100.12 -> 100.12 
100.1 -> 100.10 
100  -> 100 

변형 # 1

DecimalFormat("#,##0.00") 

100.1 -> 100.10 
but 
100 -> 100.00 

변형 # 2

: 다음의 결과를 얻을

내 경우에 어떤 패턴을 선택해야할까요?

+1

[Java에서 소수점 이하 자릿수를 반올림하는 방법] 가능한 복제본 (http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places- in-java) – piyushj

답변

3

유일한 해결책은 if 문을 사용하는 것입니다 여기에 언급 된 것처럼 : https://stackoverflow.com/a/39268176/6619441

public static boolean isInteger(BigDecimal bigDecimal) { 
    int intVal = bigDecimal.intValue(); 
    return bigDecimal.compareTo(new BigDecimal(intVal)) == 0; 
} 

public static String myFormat(BigDecimal bigDecimal) { 
    String formatPattern = isInteger(bigDecimal) ? "#,##0" : "#,##0.00"; 
    return new DecimalFormat(formatPattern).format(bigDecimal); 
} 

테스트

myFormat(new BigDecimal("100")); // 100 
myFormat(new BigDecimal("100.1")); // 100.10 

사람이 더 우아한 방법을 알고 있다면, 그것을 공유하십시오!

0

if 문이 필요하다고 생각합니다.

static double intMargin = 1e-14; 

public static String myFormat(double d) { 
    DecimalFormat format; 
    // is value an integer? 
    if (Math.abs(d - Math.round(d)) < intMargin) { // close enough 
     format = new DecimalFormat("#,##0.##"); 
    } else { 
     format = new DecimalFormat("#,##0.00"); 
    } 
    return format.format(d); 
} 

정수로 간주되는 숫자에 허용 된 여백은 상황에 따라 선택되어야합니다. 항상 정확한 정수를 가질 것이라고 가정하지 마십시오. 복식이 항상 그런 식으로 작동하지는 않습니다. 4 반환 myFormat(4) 위의 선언, myFormat(4.98) 반환 4.98myFormat(4.0001) 반환 4.00

. 내가 도달

+0

if 문을 사용하는 아이디어도 있었지만 특정 패턴의 DecimalFormat을 사용하여 좀 더 정상적으로 해결할 수 있기를 기대했습니다. – repitch

+0

'DecimalFormat'의 서브 클래스를 만들고 if 문을 서브 클래스에 넣을 수 있습니다. 그래도 나는 정말로 그 생각을 좋아하지 않는다. –