# tofixed - java除法小數點

## 如何在Java中將數字四捨五入到小數點後n位 (20)

``````String.format("%.5g%n", 0.912385);
``````

``````0.91239
``````

``````String.format("%.5g%n", 0.912300);
``````

``````0.91230
``````

``````DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);
``````

``````0.91238
``````

``````0.912385 -> 0.91239
0.912300 -> 0.9123
``````

@Milhous：舍入的十進制格式非常好：

``````DecimalFormat df = new DecimalFormat("#.00000");
df.format(0.912385);
``````

``````DecimalFormat df = new DecimalFormat("#0.######");
df.format(0.912385);
``````

``````DecimalFormat df = new DecimalFormat("#0.#####");
df.format(0.912385);
``````

``````DecimalFormat df = new DecimalFormat("#0.####");
df.format(0.912385);
``````

[編輯：如果插入符格式如此（“＃0。############”），並且為參數輸入了小數，例如3.1415926，則DecimalFormat不會產生任何垃圾例如追踪零），並將返回： `3.1415926` ..如果你是這樣傾斜。 當然，對於某些開發人員的喜好有點冗長 - 但是，嘿，它在處理過程中佔用的內存很少，並且很容易實現。]

DecimalFormat是輸出的最佳方式，但我不喜歡它。 我總是這樣做，因為它會返回雙倍的價值。 所以我可以使用它不僅僅是輸出。

``````Math.round(selfEvaluate*100000d.0)/100000d.0;
``````

``````Math.round(selfEvaluate*100000d.0)*0.00000d1;
``````

If you Consider 5 or n number of decimal. May be this answer solve your prob.

``````    double a = 123.00449;
double roundOff1 = Math.round(a*10000)/10000.00;
double roundOff2 = Math.round(roundOff1*1000)/1000.00;
double roundOff = Math.round(roundOff2*100)/100.00;

System.out.println("result:"+roundOff);
``````

Output will be: 123.0 1
this can be solve with loop and recursive function.

If you're using a technology that has a minimal JDK. Here's a way without any Java libs:

``````double scale = 100000;
double myVal = 0.912385;
double rounded = (int)((myVal * scale) + 0.5d) / scale;
``````

To achieve this we can use this formatter:

`````` DecimalFormat df = new DecimalFormat("#.00");
String resultado = df.format(valor)
``````

``````DecimalFormat df = new DecimalFormat("0.00"); :
``````

Use this method to get always two decimals:

``````   private static String getTwoDecimals(double value){
DecimalFormat df = new DecimalFormat("0.00");
return df.format(value);
}
``````

Defining this values:

``````91.32
5.22
11.5
1.2
2.6
``````

Using the method we can get this results:

``````91.32
5.22
11.50
1.20
2.60
``````

``````double pp = 10000;

double myVal = 22.268699999999967;
String needVal = "22.2687";

double i = (5.0/pp);

String format = "%10.4f";
String getVal = String.format(format,(Math.round((myVal +i)*pp)/pp)-i).trim();
``````

``````DecimalFormat df = new DecimalFormat("#.00000");
df.format(0.912385);
``````

``````BigDecimal value = new BigDecimal("2.3");
value = value.setScale(0, RoundingMode.UP);
BigDecimal value1 = new BigDecimal("-2.3");
value1 = value1.setScale(0, RoundingMode.UP);
System.out.println(value + "n" + value1);
``````

``````(double)Math.round(value * 100000d) / 100000d
``````

``````double d = 9232.129394d;
``````

``````BigDecimal bd = new BigDecimal(d).setScale(2, RoundingMode.HALF_EVEN);
d = bd.doubleValue();
``````

``````d = Math.round(d*100)/100.0d;
``````

1. ``````DecimalFormat df = new DecimalFormat("#.#####");
df.setRoundingMode(RoundingMode.HALF_UP);
String str1 = df.format(0.912385)); // 0.91239
``````
2. ``````String str2 = new BigDecimal(0.912385)
.setScale(5, BigDecimal.ROUND_HALF_UP)
.toString();
``````

1. 來自Apache Commons Math的Precision

``````double rounded = Precision.round(0.912385, 5, BigDecimal.ROUND_HALF_UP);
``````
2. Colt的Functions

``````double rounded = Functions.round(0.00001).apply(0.912385)
``````
3. 來自Weka的Utils

``````double rounded = Utils.roundDouble(0.912385, 5)
``````

``````DecimalFormat formatter = new DecimalFormat("0.0##");
formatter.setRoundingMode(RoundingMode.HALF_UP);

double num = 1.234567;
return formatter.format(num);
``````

``````double d = 3.76628729;

DecimalFormat newFormat = new DecimalFormat("#.##");
double twoDecimal =  Double.valueOf(newFormat.format(d));
``````

``````public static double round(double valueToRound, int numberOfDecimalPlaces)
{
double multipicationFactor = Math.pow(10, numberOfDecimalPlaces);
double interestedInZeroDPs = valueToRound * multipicationFactor;
return Math.round(interestedInZeroDPs) / multipicationFactor;
}
``````

`DoubleRounder`實用程序在decimal4j庫中提供了類似但快速且無垃圾的方法：

`````` double a = DoubleRounder.round(2.0/3.0, 3);
double b = DoubleRounder.round(2.0/3.0, 3, RoundingMode.DOWN);
double c = DoubleRounder.round(1000.0d, 17);
double d = DoubleRounder.round(90080070060.1d, 9);
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
``````

`````` 0.667
0.666
1000.0
9.00800700601E10
``````

• 此行為與`BigDecimal(double)`構造函數非常相似（但不包含使用字符串構造函數的`valueOf(double)` ）。
• 這個問題可以通過一個雙舍入步驟來避免，首先是更高的精度，但這很複雜，我不打算在這裡詳細討論

``````public class RoundingCounterExample
{

static float roundOff(float x, int position)
{
float a = x;
double temp = Math.pow(10.0, position);
a *= temp;
a = Math.round(a);
return (a / (float)temp);
}

public static void main(String[] args)
{
float a = roundOff(0.0009434f,3);
System.out.println("a="+a+" (a % .001)="+(a % 0.001));
int count = 0, errors = 0;
for (double x = 0.0; x < 1; x += 0.0001)
{
count++;
double d = x;
int scale = 2;
double factor = Math.pow(10, scale);
d = Math.round(d * factor) / factor;
if ((d % 0.01) != 0.0)
{
System.out.println(d + " " + (d % 0.01));
errors++;
}
}
System.out.println(count + " trials " + errors + " errors");
}
}
``````

``````10001 trials 9251 errors
``````

``````public static void main(String[] args)
{
int count = 0, errors = 0;
int scale = 2;
double factor = Math.pow(10, scale);
MathContext mc = new MathContext(16, RoundingMode.DOWN);
for (double x = 0.0; x < 1; x += 0.0001)
{
count++;
double d = x;
d = Math.round(d * factor) / factor;
BigDecimal bd = new BigDecimal(d, mc);
bd = bd.remainder(new BigDecimal("0.01"), mc);
if (bd.multiply(BigDecimal.valueOf(100)).remainder(BigDecimal.ONE, mc).compareTo(BigDecimal.ZERO) != 0)
{
System.out.println(d + " " + bd);
errors++;
}
}
System.out.println(count + " trials " + errors + " errors");
}
``````

``````10001 trials 4401 errors
``````

``````public static double round(double x, int scale) {
return round(x, scale, BigDecimal.ROUND_HALF_UP);
}

public static double round(double x, int scale, int roundingMethod) {
try {
return (new BigDecimal
(Double.toString(x))
.setScale(scale, roundingMethod))
.doubleValue();
} catch (NumberFormatException ex) {
if (Double.isInfinite(x)) {
return x;
} else {
return Double.NaN;
}
}
}
``````

``````  Locale locale = Locale.ENGLISH;
NumberFormat nf = NumberFormat.getNumberInstance(locale);
// for trailing zeros:
nf.setMinimumFractionDigits(2);
// round to 2 digits:
nf.setMaximumFractionDigits(2);

System.out.println(nf.format(.99));
System.out.println(nf.format(123.567));
System.out.println(nf.format(123.0));
``````

Will print in English locale (no matter what your locale is): 0.99 123.57 123.00

The example is taken from Farenda - how to convert double to String correctly .

``````DecimalFormat myFormatter = new DecimalFormat("0.000");
String output = myFormatter.format(2.34d);
``````

``````double myNum = .912385;
int precision = 10000; //keep 4 digits
myNum= Math.floor(myNum * precision +.5)/precision;
``````