どのようにも形式浮体式数の文字列に無理なく小数0?
-
22-08-2019 - |
質問
は、64-bitダブルを表すことができますの整数+/-253 正確に
このような状を選択し用のダブルタイプとしてシングルタイプのための全ての種類、私の最大の整数を符号なし32ビットとしています。
今はこんなものがあるようで印刷がこれらの疑似整数を表すが、問題はも混合で実際に表示されます。
どのようにしてい印刷倍にもJava?
していました String.format("%f", value)
, であり、私は多くの末尾のゼロをめに小さな値です。
この例の出力の %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...)
は ロケール依存 (答えます。
解決
ここでは印刷の整数として格納されたdouble値としてその整数、その他印刷のdoubleを必要最小限の精度
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"
このため、コメントの中にあるこの右側の回答の質問です。
とはいうものの、有用な方法でフォーマット番号不要末尾のゼロのままにしてお
String.format("%.2f", value) ;
短:
いく末尾のゼロ、ロケールに問題を使います:
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
使用科学表記の場合ダブル未満10^-3は以上10^7double myValue = 0.00000021d; String.format("%s", myvalue); //output: 2.1E-7
を使用
%f
, デフォルト数の精度は6,除きhardcodeでも結果のエクストラゼロの場合には追加で以下である.例:double myValue = 0.00000021d; String.format("%.12f", myvalue); //output: 0.000000210000
を使用
setMaximumFractionDigits(0);
または%.0f
まず小数点精度、微細なたは整数/longなダブル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
るequals340Double.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);
}
"それでは、最初の曲を聞います。
性能による損失の文字列操作がゼロであるようにします。
このコードにパンフレット、ホームページの終了後 %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値、もしインターネットで商用アニメーション文字列:
double horribleNumber = 3598945.141658554548844;
DoubleFormatter df = new DoubleFormatter(4,6); //4 = MaxInteger, 6 = MaxDecimal
String beautyDisplay = df.format(horribleNumber);
- 場合の数値の整数部V以上MaxInteger=>表示V研究員フォーマット(1.2345e+30) その他の表示は通常の形式124.45678.
- のMaxDecimal決定番号の桁のエントリーと銀行四捨五入)
こちらのコード:
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();
}
}
注意:使用した2機能からグァバの図書館があります。組み合わせて使用しない場合はグアバ、コード、あるいは自分自身
/**
* 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();
}
を使用 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);
}
}
遅い回答ですが---
くお願いします 選択 お客様の数の ダブルタイプ.この根本問題で軍き 整数 へのdouble(およびそのため、初期に関する情報は価値の。う保管数のインスタンス 番号 クラスのスーパークラスダブルともとの整数)に依存する多型を決定する正しい形式のかかりますか?
しかできない場合があり可refactor全体のコードによりそのものを作り出すことのできる希望の出力のブラウザでクッキーコード/鋳造/解析.
例:
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
たく違反ソナー報告
こうした:
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桁桁を表します。では、decimalformat.が必要な場合は小数点の位置が末尾のゼロをこの作品です。
String s = "1.210000";
while (s.endsWith("0")){
s = (s.substring(0, s.length() - 1));
}
この文字列の尾鉱0-sです。