불필요한 10 진수 0없이 플로팅 숫자를 문자열로 멋지게 형식화하는 방법은 무엇입니까?
-
22-08-2019 - |
문제
64 비트 더블은 정수 +/- 2를 나타낼 수 있습니다53 바로 그거죠
이 사실을 감안할 때 나는 가장 큰 정수가 서명되지 않은 32 비트이기 때문에 모든 유형에 대한 이중 유형을 단일 유형으로 사용하기로 선택했습니다.
그러나 지금 나는이 의사 정수를 인쇄해야하지만 문제는 실제 복식과 혼합되어 있다는 것입니다.
그렇다면 자바 에서이 두 배를 잘 인쇄하려면 어떻게해야합니까?
나는 시도했다 String.format("%f", value)
, 작은 값에 대한 많은 후행 0을 얻는 것을 제외하고는 가깝습니다.
다음은 OF의 예제입니다 %f
232.00000000 0.18000000000 1237875192.0 4.5800000000 0.00000000 1.23450000
내가 원하는 것은 :
232 0.18 1237875192 4.58 0 1.2345
물론 제로를 다듬기 위해 함수를 쓸 수 있지만 문자열 조작으로 인한 성능 손실이 많습니다. 다른 형식 코드로 더 잘할 수 있습니까?
편집하다
Tom E.와 Jeremy S.의 답변은 둘 다 십진수 2 곳으로 임의로 반올림하기 때문에 용납 할 수 없습니다. 대답하기 전에 문제를 이해하십시오.
편집 2
점에 유의하시기 바랍니다 String.format(format, args...)
~이다 로케일 의존적 (아래 답변 참조).
해결책
아이디어가 정수 인 것처럼 두 배로 저장된 정수를 인쇄하고, 그렇지 않으면 필요한 최소 정밀도로 복식을 인쇄하는 경우 :
public static String fmt(double d)
{
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
생산 :
232
0.18
1237875192
4.58
0
1.2345
문자열 조작에 의존하지 않습니다.
다른 팁
new DecimalFormat("#.##").format(1.199); //"1.2"
의견에 지적한 바와 같이, 이것은 원래 질문에 대한 정답이 아닙니다.
즉, 불필요한 후행 0을 차지하지 않고 숫자를 포맷하는 매우 유용한 방법입니다.
String.format("%.2f", value) ;
요컨대 :
후행 0 및 로케일 문제를 제거하려면 다음을 사용해야합니다.
double myValue = 0.00000021d;
DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); //340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
System.out.println(df.format(myValue)); //output: 0.00000021
설명:
다른 답변이 나에게 적합하지 않은 이유 :
Double.toString()
또는System.out.println
또는FloatingDecimal.toJavaFormatString
Double이 10^-3 미만인 경우 과학 표기법을 사용합니다.double myValue = 0.00000021d; String.format("%s", myvalue); //output: 2.1E-7
사용하여
%f
, 기본 소수 정밀도는 6입니다. 그렇지 않으면 하드 코드를 할 수 있지만 소수점이 적은 경우 추가 0이 추가됩니다. 예시 :double myValue = 0.00000021d; String.format("%.12f", myvalue); //output: 0.000000210000
사용하여
setMaximumFractionDigits(0);
또는%.0f
소수점 정밀도를 제거합니다. 정수/긴에는 적합하지만 더블에는 적합하지 않습니다.double myValue = 0.00000021d; System.out.println(String.format("%.0f", myvalue)); //output: 0 DecimalFormat df = new DecimalFormat("0"); System.out.println(df.format(myValue)); //output: 0
DecimalFormat을 사용하면 로컬 의존적입니다. 프랑스 로케일에서는 소수점 분리기가 쉼표입니다.
double myValue = 0.00000021d; DecimalFormat df = new DecimalFormat("0"); df.setMaximumFractionDigits(340); System.out.println(df.format(myvalue));//output: 0,00000021
영어 로케일을 사용하면 프로그램이 실행되는 곳 어디에서나 소수점 분리기에 대한 포인트를 얻을 수 있습니다.
그때 340을 사용하는 이유 setMaximumFractionDigits
?
두 가지 이유 :
setMaximumFractionDigits
정수를 허용하지만 구현에는 최대 숫자가 허용됩니다.DecimalFormat.DOUBLE_FRACTION_DIGITS
340과 같습니다Double.MIN_VALUE = 4.9E-324
따라서 340 자리로 두 배와 느슨한 정밀도를 반올림하지 않을 것입니다.
왜 안 돼:
if (d % 1.0 != 0)
return String.format("%s", d);
else
return String.format("%.0f",d);
이것은 이중으로 지원되는 극단적 값으로 작동해야합니다. 수확량 :
0.12
12
12.144252
0
내 2 센트 :
if(n % 1 == 0) {
return String.format(Locale.US, "%.0f", n));
} else {
return String.format(Locale.US, "%.1f", n));
}
내 컴퓨터에서 다음 함수는 제공 한 기능보다 약 7 배 빠릅니다. Jasond의 대답, 그것은 피하기 때문에 String.format
:
public static String prettyPrint(double d) {
int i = (int) d;
return d == i ? String.valueOf(i) : String.valueOf(d);
}
아뇨, 신경 쓰지 마세요.
문자열 조작으로 인한 성능 손실은 0입니다.
그리고 다음은 끝을 다듬는 코드입니다. %f
private static String trimTrailingZeros(String number) {
if(!number.contains(".")) {
return number;
}
return number.replaceAll("\\.?0*$", "");
}
if (d == Math.floor(d)) {
return String.format("%.0f", d);
} else {
return Double.toString(d);
}
점에 유의하시기 바랍니다 String.format(format, args...)
~이다 로케일 의존적 형식이기 때문에 사용자의 기본 로케일 사용 즉, 아마도 쉼표와 심지어 내부의 공간이 있습니다. 123 456,789 또는 123,456.789, 그것은 당신이 기대하는 것이 아닐 수도 있습니다.
사용하는 것을 선호 할 수 있습니다 String.format((Locale)null, format, args...)
.
예를 들어,
double f = 123456.789d;
System.out.println(String.format(Locale.FRANCE,"%f",f));
System.out.println(String.format(Locale.GERMANY,"%f",f));
System.out.println(String.format(Locale.US,"%f",f));
인쇄물
123456,789000
123456,789000
123456.789000
그리고 이것이 바로 할 것입니다 String.format(format, args...)
다른 나라에서하십시오.
공식에 대한 토론이 있었기 때문에 OK 편집 :
res += stripFpZeroes(String.format((Locale) null, (nDigits!=0 ? "%."+nDigits+"f" : "%f"), value));
...
protected static String stripFpZeroes(String fpnumber) {
int n = fpnumber.indexOf('.');
if (n == -1) {
return fpnumber;
}
if (n < 2) {
n = 2;
}
String s = fpnumber;
while (s.length() > n && s.endsWith("0")) {
s = s.substring(0, s.length()-1);
}
return s;
}
나는 만들었다 DoubleFormatter
많은 수의 이중 값을 니스/발표 가능한 문자열로 효율적으로 변환하려면 다음과 같습니다.
double horribleNumber = 3598945.141658554548844;
DoubleFormatter df = new DoubleFormatter(4,6); //4 = MaxInteger, 6 = MaxDecimal
String beautyDisplay = df.format(horribleNumber);
- V의 정수 부분에 Maxinteger => Display V보다 과학자 형식 (1.2345e+30)이 더 많으면 정상 형식 124.45678로 표시됩니다.
- Maxdecimal Dection Decling Decins 수수료 숫자 (Banker 's Rounding과 함께 트림)
여기 코드 :
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
/**
* Convert a double to a beautiful String (US-local):
*
* double horribleNumber = 3598945.141658554548844;
* DoubleFormatter df = new DoubleFormatter(4,6);
* String beautyDisplay = df.format(horribleNumber);
* String beautyLabel = df.formatHtml(horribleNumber);
*
* Manipulate 3 instances of NumberFormat to efficiently format a great number of double values.
* (avoid to create an object NumberFormat each call of format()).
*
* 3 instances of NumberFormat will be reused to format a value v:
*
* if v < EXP_DOWN, uses nfBelow
* if EXP_DOWN <= v <= EXP_UP, uses nfNormal
* if EXP_UP < v, uses nfAbove
*
* nfBelow, nfNormal and nfAbove will be generated base on the precision_ parameter.
*
* @author: DUONG Phu-Hiep
*/
public class DoubleFormatter
{
private static final double EXP_DOWN = 1.e-3;
private double EXP_UP; // always = 10^maxInteger
private int maxInteger_;
private int maxFraction_;
private NumberFormat nfBelow_;
private NumberFormat nfNormal_;
private NumberFormat nfAbove_;
private enum NumberFormatKind {Below, Normal, Above}
public DoubleFormatter(int maxInteger, int maxFraction){
setPrecision(maxInteger, maxFraction);
}
public void setPrecision(int maxInteger, int maxFraction){
Preconditions.checkArgument(maxFraction>=0);
Preconditions.checkArgument(maxInteger>0 && maxInteger<17);
if (maxFraction == maxFraction_ && maxInteger_ == maxInteger) {
return;
}
maxFraction_ = maxFraction;
maxInteger_ = maxInteger;
EXP_UP = Math.pow(10, maxInteger);
nfBelow_ = createNumberFormat(NumberFormatKind.Below);
nfNormal_ = createNumberFormat(NumberFormatKind.Normal);
nfAbove_ = createNumberFormat(NumberFormatKind.Above);
}
private NumberFormat createNumberFormat(NumberFormatKind kind) {
final String sharpByPrecision = Strings.repeat("#", maxFraction_); //if you do not use Guava library, replace with createSharp(precision);
NumberFormat f = NumberFormat.getInstance(Locale.US);
//Apply banker's rounding: this is the rounding mode that statistically minimizes cumulative error when applied repeatedly over a sequence of calculations
f.setRoundingMode(RoundingMode.HALF_EVEN);
if (f instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) f;
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
//set group separator to space instead of comma
//dfs.setGroupingSeparator(' ');
//set Exponent symbol to minus 'e' instead of 'E'
if (kind == NumberFormatKind.Above) {
dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
} else {
dfs.setExponentSeparator("e");
}
df.setDecimalFormatSymbols(dfs);
//use exponent format if v is out side of [EXP_DOWN,EXP_UP]
if (kind == NumberFormatKind.Normal) {
if (maxFraction_ == 0) {
df.applyPattern("#,##0");
} else {
df.applyPattern("#,##0."+sharpByPrecision);
}
} else {
if (maxFraction_ == 0) {
df.applyPattern("0E0");
} else {
df.applyPattern("0."+sharpByPrecision+"E0");
}
}
}
return f;
}
public String format(double v) {
if (Double.isNaN(v)) {
return "-";
}
if (v==0) {
return "0";
}
final double absv = Math.abs(v);
if (absv<EXP_DOWN) {
return nfBelow_.format(v);
}
if (absv>EXP_UP) {
return nfAbove_.format(v);
}
return nfNormal_.format(v);
}
/**
* format and higlight the important part (integer part & exponent part)
*/
public String formatHtml(double v) {
if (Double.isNaN(v)) {
return "-";
}
return htmlize(format(v));
}
/**
* This is the base alogrithm: create a instance of NumberFormat for the value, then format it. It should
* not be used to format a great numbers of value
*
* We will never use this methode, it is here only to understanding the Algo principal:
*
* format v to string. precision_ is numbers of digits after decimal.
* if EXP_DOWN <= abs(v) <= EXP_UP, display the normal format: 124.45678
* otherwise display scientist format with: 1.2345e+30
*
* pre-condition: precision >= 1
*/
@Deprecated
public String formatInefficient(double v) {
final String sharpByPrecision = Strings.repeat("#", maxFraction_); //if you do not use Guava library, replace with createSharp(precision);
final double absv = Math.abs(v);
NumberFormat f = NumberFormat.getInstance(Locale.US);
//Apply banker's rounding: this is the rounding mode that statistically minimizes cumulative error when applied repeatedly over a sequence of calculations
f.setRoundingMode(RoundingMode.HALF_EVEN);
if (f instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) f;
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
//set group separator to space instead of comma
dfs.setGroupingSeparator(' ');
//set Exponent symbol to minus 'e' instead of 'E'
if (absv>EXP_UP) {
dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
} else {
dfs.setExponentSeparator("e");
}
df.setDecimalFormatSymbols(dfs);
//use exponent format if v is out side of [EXP_DOWN,EXP_UP]
if (absv<EXP_DOWN || absv>EXP_UP) {
df.applyPattern("0."+sharpByPrecision+"E0");
} else {
df.applyPattern("#,##0."+sharpByPrecision);
}
}
return f.format(v);
}
/**
* Convert "3.1416e+12" to "<b>3</b>.1416e<b>+12</b>"
* It is a html format of a number which highlight the integer and exponent part
*/
private static String htmlize(String s) {
StringBuilder resu = new StringBuilder("<b>");
int p1 = s.indexOf('.');
if (p1>0) {
resu.append(s.substring(0, p1));
resu.append("</b>");
} else {
p1 = 0;
}
int p2 = s.lastIndexOf('e');
if (p2>0) {
resu.append(s.substring(p1, p2));
resu.append("<b>");
resu.append(s.substring(p2, s.length()));
resu.append("</b>");
} else {
resu.append(s.substring(p1, s.length()));
if (p1==0){
resu.append("</b>");
}
}
return resu.toString();
}
}
참고 : Guava Library의 2 가지 기능을 사용했습니다. Guava를 사용하지 않으면 직접 코딩하십시오.
/**
* Equivalent to Strings.repeat("#", n) of the Guava library:
*/
private static String createSharp(int n) {
StringBuilder sb = new StringBuilder();
for (int i=0;i<n;i++) {
sb.append('#');
}
return sb.toString();
}
a DecimalFormat
그리고 setMinimumFractionDigits(0)
이것은 일을 잘 수행 할 것이고, 나는 주제가 오래되었음을 알고 있지만, 나는 이것에 올 때까지 같은 문제로 어려움을 겪고있었습니다. 누군가가 유용하다고 생각하기를 바랍니다.
public static String removeZero(double number) {
DecimalFormat format = new DecimalFormat("#.###########");
return format.format(number);
}
new DecimalFormat("00.#").format(20.236)
//out =20.2
new DecimalFormat("00.#").format(2.236)
//out =02.2
- 최소 숫자 수는 0입니다
- 렌더 # 숫자
String s = String.valueof("your int variable");
while (g.endsWith("0") && g.contains(".")) {
g = g.substring(0, g.length() - 1);
if (g.endsWith("."))
{
g = g.substring(0, g.length() - 1);
}
}
늦은 답변이지만 ...
당신은 당신을 말했습니다 선택하다 당신의 숫자를 보관합니다 이중 유형. 나는 이것이 당신이 저장해야하기 때문에 문제의 근원 일 수 있다고 생각합니다. 정수 복식으로 (따라서 가치의 특성에 대한 초기 정보를 잃어 버리기). 사례에 숫자를 저장하는 것은 어떻습니까 숫자 클래스 (이중 및 정수의 슈퍼 클래스) 및 다형성에 의존하여 각 숫자의 올바른 형식을 결정합니까?
코드의 전체 부분을 리팩터링하는 것은 허용되지 않을 수도 있지만 추가 코드/캐스팅/구문 분석없이 원하는 출력을 생성 할 수 있습니다.
예시:
import java.util.ArrayList;
import java.util.List;
public class UseMixedNumbers {
public static void main(String[] args) {
List<Number> listNumbers = new ArrayList<Number>();
listNumbers.add(232);
listNumbers.add(0.18);
listNumbers.add(1237875192);
listNumbers.add(4.58);
listNumbers.add(0);
listNumbers.add(1.2345);
for (Number number : listNumbers) {
System.out.println(number);
}
}
}
다음 출력을 생성합니다.
232
0.18
1237875192
4.58
0
1.2345
public static String fmt(double d) {
String val = Double.toString(d);
String[] valArray = val.split("\\.");
long valLong = 0;
if(valArray.length == 2){
valLong = Long.parseLong(valArray[1]);
}
if (valLong == 0)
return String.format("%d", (long) d);
else
return String.format("%s", d);
}
나는이 원인을 사용해야했다 d == (long)d
Sonar 보고서에서 위반을주었습니다
이것이 제가 생각해 낸 것입니다.
private static String format(final double dbl) {
return dbl % 1 != 0 ? String.valueOf(dbl) : String.valueOf((int) dbl);
}
간단한 하나의 라이너, 실제로 필요한 경우 int에만 캐스트됩니다.
이를 달성하는 두 가지 방법이 있습니다. 첫째, 짧은 (그리고 아마도 더 나은) 방법 :
public static String formatFloatToString(final float f)
{
final int i=(int)f;
if(f==i)
return Integer.toString(i);
return Float.toString(f);
}
그리고 여기 더 길고 아마도 더 나쁜 방법이 있습니다.
public static String formatFloatToString(final float f)
{
final String s=Float.toString(f);
int dotPos=-1;
for(int i=0;i<s.length();++i)
if(s.charAt(i)=='.')
{
dotPos=i;
break;
}
if(dotPos==-1)
return s;
int end=dotPos;
for(int i=dotPos+1;i<s.length();++i)
{
final char c=s.charAt(i);
if(c!='0')
end=i+1;
}
final String result=s.substring(0,end);
return result;
}
다음은 실제로 작동하는 답변입니다 (여기서 다른 답변의 조합)
public static String removeTrailingZeros(double f)
{
if(f == (int)f) {
return String.format("%d", (int)f);
}
return String.format("%f", f).replaceAll("0*$", "");
}
나는 이것이 정말 오래된 실이라는 것을 알고 있습니다. 그러나 이것을하는 가장 좋은 방법은 다음과 같습니다.
public class Test {
public static void main(String args[]){
System.out.println(String.format("%s something",new Double(3.456)));
System.out.println(String.format("%s something",new Double(3.456234523452)));
System.out.println(String.format("%s something",new Double(3.45)));
System.out.println(String.format("%s something",new Double(3)));
}
}
산출:
3.456 something
3.456234523452 something
3.45 something
3.0 something
유일한 문제는 .0이 제거되지 않는 마지막 문제입니다. 그러나 당신이 그것으로 살 수 있다면 이것은 가장 잘 작동합니다. %.2f는 마지막 2 자리 숫자로 반올림합니다. 소수판도 마찬가지입니다. 소수점이 모두가 필요하지만 후행 제로가 필요하지 않은 경우 가장 잘 작동합니다.
String s = "1.210000";
while (s.endsWith("0")){
s = (s.substring(0, s.length() - 1));
}
이렇게하면 스트링이 테일링 0-s를 떨어 뜨릴 수 있습니다.