Jak ładnie sformatować liczby pływające na ciąg bez zbędnego dziesiętnego 0?
64-bitowy podwójny może reprezentować liczbę całkowitą +/- 253 dokładnie
Biorąc pod uwagę ten fakt, wybieram użycie typu podwójnego jako pojedynczego dla wszystkich moich typów, ponieważ moja największa liczba całkowita jest niepodpisana 32-bitowo.
Ale teraz muszę wydrukować te pseudo liczby całkowite, ale problem w tym, że są one również mieszane z rzeczywistymi sobowtórami.
Więc jak ładnie wydrukować te duble w Javie?
Próbowałem String.format("%f", value)
, który jest blisko, z tym, że dostaję dużo końcowych zer dla małych wartości.
Oto Przykładowe wyjście z %f
232.00000000 0.18000000000 1237875192.0 4.5800000000 0.00000000 1.23450000
Chcę:
232 0.18 1237875192 4.58 0 1.2345
Jasne, że mogę napisać funkcję do przycinania zer, ale to duża strata wydajności z powodu manipulacji łańcuchami. Czy Mogę zrobić lepiej z innym kodem formatu?
EDIT
Odpowiedzi Toma E. i Jeremy ' ego S. są niedopuszczalne, ponieważ obie arbitralnie zaokrąglają się do 2 miejsc po przecinku. Proszę zrozumieć problem przed odpowiedzią.
Edytuj 2
Należy pamiętać, że String.format(format, args...)
jest zależne od lokalizacji (zobacz Odpowiedzi poniżej).
22 answers
Jeśli chodzi o drukowanie liczb całkowitych przechowywanych jako liczby podwójne, tak jakby były liczbami całkowitymi, a w przeciwnym razie drukowanie liczb podwójnych z minimalną wymaganą precyzją:
public static String fmt(double d)
{
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
Produkuje:
232
0.18
1237875192
4.58
0
1.2345
I nie polega na manipulacji łańcuchami.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-14 19:59:42
new DecimalFormat("#.##").format(1.199); //"1.2"
Jak zaznaczono w komentarzach, nie jest to właściwa odpowiedź na pierwotne pytanie.
To powiedziawszy, jest to bardzo przydatny sposób formatowania liczb bez zbędnych końcowych zer.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-28 04:22:47
String.format("%.2f", value) ;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-04 00:35:09
W skrócie:
Jeśli chcesz pozbyć się problemów z końcowymi zerami i Locale, powinieneś użyć :
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
Explanation:
Dlaczego inne odpowiedzi mi nie odpowiadały:
-
Double.toString()
lubSystem.out.println
lubFloatingDecimal.toJavaFormatString
używa notacji naukowych, jeśli podwójne jest mniejsze niż 10^-3 lub większe lub równe 10^7double myValue = 0.00000021d; String.format("%s", myvalue); //output: 2.1E-7
-
Używając
%f
, domyślna precyzja dziesiętna wynosi 6, w przeciwnym razie możesz ją zakodować na twardo, ale powoduje to dodatkowe dodawane zera, jeśli masz mniej miejsc po przecinku. Przykład:double myValue = 0.00000021d; String.format("%.12f", myvalue); //output: 0.000000210000
-
Używając
setMaximumFractionDigits(0);
lub%.0f
usuwasz dowolną precyzję dziesiętną, która jest dobra dla liczb całkowitych/długich, ale nie dla podwójnychdouble 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
-
Używając DecimalFormat, jesteś zależny od miejsca. W języku francuskim separatorem dziesiętnym jest przecinek, a nie Punkt:
double myValue = 0.00000021d; DecimalFormat df = new DecimalFormat("0"); df.setMaximumFractionDigits(340); System.out.println(df.format(myvalue));//output: 0,00000021
Używanie angielskich ustawień regionalnych gwarantuje, że otrzymasz punkt dla separatora dziesiętnego, gdziekolwiek Twój program będzie działał
Dlaczego używając 340 wtedy dla setMaximumFractionDigits
?
Dwa powody:
-
setMaximumFractionDigits
akceptuje liczbę całkowitą, ale jej implementacja ma maksymalną dozwoloną liczbę cyfrDecimalFormat.DOUBLE_FRACTION_DIGITS
, która wynosi 340 -
Double.MIN_VALUE = 4.9E-324
więc z 340 cyframi na pewno nie zaokrąglasz swojej podwójnej i luźnej precyzji
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-09 22:48:11
Dlaczego nie:
if (d % 1.0 != 0)
return String.format("%s", d);
else
return String.format("%.0f",d);
Powinno to działać z wartościami ekstremalnymi wspieranymi przez Double. Wydajność:
0.12
12
12.144252
0
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-01 00:53:59
Na moim komputerze następująca funkcja jest około 7 razy szybsza niż funkcja dostarczona przez odpowiedź Jasonda , ponieważ unika String.format
:
public static String prettyPrint(double d) {
int i = (int) d;
return d == i ? String.valueOf(i) : String.valueOf(d);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:33:24
Moje 2 grosze:
if(n % 1 == 0) {
return String.format(Locale.US, "%.0f", n));
} else {
return String.format(Locale.US, "%.1f", n));
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-05 09:36:45
Nie, nieważne.
Utrata wydajności z powodu manipulacji łańcuchem wynosi zero.
A oto kod do przycinania końca po %f
private static String trimTrailingZeros(String number) {
if(!number.contains(".")) {
return number;
}
return number.replaceAll("\\.?0*$", "");
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-15 17:13:01
Należy pamiętać, że String.format(format, args...)
jest zależne od lokalizacji ponieważ formatuje używając domyślnych ustawień regionalnych użytkownika, to znaczy prawdopodobnie z przecinkami, a nawet spacjami wewnątrz 123 456,789 lub 123,456.789, co może nie być dokładnie tym, czego oczekujesz.
Możesz użyć String.format((Locale)null, format, args...)
.
Na przykład,
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));
Druki
123456,789000
123456,789000
123456.789000
I to będzie robić w różnych krajach.
Edytuj Ok, ponieważ było dyskusja o formalnościach:
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-16 08:02:21
Zrobiłem DoubleFormatter
aby skutecznie przekonwertować dużą liczbę podwójnych wartości na ładny / reprezentacyjny ciąg znaków:
double horribleNumber = 3598945.141658554548844;
DoubleFormatter df = new DoubleFormatter(4,6); //4 = MaxInteger, 6 = MaxDecimal
String beautyDisplay = df.format(horribleNumber);
- jeżeli całkowita Część V ma więcej niż MaxInteger = > wyświetla V w formacie (1.2345 e + 30) w przeciwnym razie wyświetl w normalnym formacie 124.45678.
- MaxDecimal decyduje o liczbie cyfr dziesiętnych (trim z zaokrągleniem bankiera)
Tutaj kod:
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();
}
}
Uwaga: użyłem 2 funkcji z biblioteki GUAVA. Jeśli nie używasz guawy, Zakoduj ją siebie:
/**
* 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();
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-21 13:03:51
if (d == Math.floor(d)) {
return String.format("%.0f", d);
} else {
return Double.toString(d);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-29 10:33:07
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);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-22 20:09:42
Ta będzie dobrze wykonana, wiem, że temat jest stary, ale zmagałem się z tym samym problemem, dopóki nie doszedłem do tego. Mam nadzieję, że komuś się przyda.
public static String removeZero(double number) {
DecimalFormat format = new DecimalFormat("#.###########");
return format.format(number);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-10 07:09:56
new DecimalFormat("00.#").format(20.236)
//out =20.2
new DecimalFormat("00.#").format(2.236)
//out =02.2
- 0 dla minimalnej liczby cyfr
- renderuje # cyfry
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-15 04:46:19
Późna odpowiedź, ale...
Powiedziałeś, że Wybierz , aby zapisać swoje numery z podwójnym typem . Myślę, że to może być źródłem problemu, ponieważ zmusza cię do przechowywania liczb całkowitych w podwójne (i tym samym utraty początkowej informacji o naturze wartości). A co z przechowywaniem liczb w instancjach klasy Number (superclass of both Double and Integer) i poleganiem na polimorfizmie w celu określenia poprawnego formatu każdej liczby ?
Wiem, że refaktorowanie całej części kodu może być niedopuszczalne z tego powodu, ale może to spowodować pożądane wyjście bez dodatkowego kodu / odlewania/parsowania.
Przykład:
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);
}
}
}
Wygeneruje następujące Wyjście:
232
0.18
1237875192
4.58
0
1.2345
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-23 08:32:54
Użyj DecimalFormat
i setMinimumFractionDigits(0)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-10 19:59:21
Oto dwa sposoby, aby to osiągnąć. Po pierwsze krótszy (i chyba lepszy) sposób:
public static String formatFloatToString(final float f)
{
final int i=(int)f;
if(f==i)
return Integer.toString(i);
return Float.toString(f);
}
A oto dłuższy i chyba gorszy sposób:
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-21 14:12:03
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);
}
Musiałem użyć tej przyczyny d == (long)d
było to naruszenie w raporcie sonaru
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-25 11:45:23
Oto co wymyśliłem:
private static String format(final double dbl) {
return dbl % 1 != 0 ? String.valueOf(dbl) : String.valueOf((int) dbl);
}
Prosty jeden liner, tylko rzuca do int, jeśli naprawdę trzeba
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-11 17:45:13
Oto odpowiedź, która faktycznie działa (kombinacja różnych odpowiedzi tutaj)
public static String removeTrailingZeros(double f)
{
if(f == (int)f) {
return String.format("%d", (int)f);
}
return String.format("%f", f).replaceAll("0*$", "");
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-23 18:41:32
Wiem, że to naprawdę stary wątek.. Ale myślę, że najlepszym sposobem, aby to zrobić jest jak poniżej:
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)));
}
}
Wyjście:
3.456 something
3.456234523452 something
3.45 something
3.0 something
Jedynym problemem jest ostatni, gdzie .0 nie zostaje usunięte. Ale jeśli jesteś w stanie z tym żyć, to działa najlepiej. %.2f zaokrągli go do ostatnich 2 cyfr dziesiętnych. Tak samo jak DecimalFormat. Jeśli potrzebujesz wszystkich miejsc po przecinku, ale nie końcowych zer, to działa to najlepiej.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-14 03:46:28
String s = "1.210000";
while (s.endsWith("0")){
s = (s.substring(0, s.length() - 1));
}
Spowoduje to, że łańcuch spadnie na 0-s.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-26 12:39:25