Can I do it with System.out.print?
You can use the printf method, like so:
System.out.printf("%.2f", val);
In short, the %.2f syntax tells Java to return your variable (val) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
There are other conversion characters you can use besides f:
d: decimal integer
o: octal integer
e: floating-point in scientific notation
You can use DecimalFormat. One way to use it:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));
Another one is to construct it using the #.## format.
I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.
I would suggest using String.format() if you need the value as a String in your code.
For example, you can use String.format() in the following way:
float myFloat = 2.001f;
String formattedString = String.format("%.02f", myFloat);
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
float f = 102.236569f;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24
You may use this quick codes below that changed itself at the end. Add how many zeros as refers to after the point
float y1 = 0.123456789;
DecimalFormat df = new DecimalFormat("#.00");
y1 = Float.valueOf(df.format(y1));
The variable y1 was equals to 0.123456789 before. After the code it turns into 0.12 only.
float floatValue=22.34555f;
System.out.print(String.format("%.2f", floatValue));
Output is 22.35.
If you need 3 decimal points change it to "%.3f".
Many people have mentioned DecimalFormat. But you can also use printf if you have a recent version of Java:
System.out.printf("%1.2f", 3.14159D);
See the docs on the Formatter for more information about the printf format string.
A simple trick is to generate a shorter version of your variable by multiplying it with e.g. 100, rounding it and dividing it by 100.0 again. This way you generate a variable, with 2 decimal places:
double new_variable = Math.round(old_variable*100) / 100.0;
This "cheap trick" was always good enough for me, and works in any language (I am not a Java person, just learning it).
Look at DecimalFormat
Here is an example from the tutorial:
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
If you choose a pattern like "###.##", you will get two decimal places, and I think that the values are rounded up. You will want to look at the link to get the exact format you want (e.g., whether you want trailing zeros)
To print a float up to 2 decimal places in Java:
float f = (float)11/3;
System.out.print(String.format("%.2f",f));
OUTPUT: 3.67
> use %.3f for up to three decimal places.
Below is code how you can display an output of float data with 2 decimal places in Java:
float ratingValue = 52.98929821f;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsFR = Float.valueOf(decimalFormat.format(ratingValue)); // output is 52.98
OK - str to float.
package test;
import java.text.DecimalFormat;
public class TestPtz {
public static void main(String[] args) {
String preset0 = "0.09,0.20,0.09,0.07";
String[] thisto = preset0.split(",");
float a = (Float.valueOf(thisto[0])).floatValue();
System.out.println("[Original]: " + a);
a = (float) (a + 0.01);
// Part 1 - for display / debug
System.out.printf("[Local]: %.2f \n", a);
// Part 2 - when value requires to be send as it is
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
System.out.println("[Remote]: " + df.format(a));
}
}
Output:
run:
[Original]: 0.09
[Local]: 0.10
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)
One issue that had me for an hour or more, on DecimalFormat- It handles double and float inputs differently. Even change of RoundingMode did not help. I am no expert but thought it may help someone like me. Ended up using Math.round instead.
See below:
DecimalFormat df = new DecimalFormat("#.##");
double d = 0.7750;
System.out.println(" Double 0.7750 -> " +Double.valueOf(df.format(d)));
float f = 0.7750f;
System.out.println(" Float 0.7750f -> "+Float.valueOf(df.format(f)));
// change the RoundingMode
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(" Rounding Up Double 0.7750 -> " +Double.valueOf(df.format(d)));
System.out.println(" Rounding Up Float 0.7750f -> " +Float.valueOf(df.format(f)));
Output:
Double 0.7750 -> 0.78
Float 0.7750f -> 0.77
Rounding Up Double 0.7750 -> 0.78
Rounding Up Float 0.7750f -> 0.77
public String getDecimalNumber(String number) {
Double d=Double.parseDouble(number);
return String.format("%.5f", d);
}
Take care of NumberFormatException as well
small simple program for demonstration:
import java.io.*;
import java.util.Scanner;
public class twovalues {
public static void main(String args[]) {
float a,b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Values For Calculation");
a=sc.nextFloat();
b=sc.nextFloat();
float c=a/b;
System.out.printf("%.2f",c);
}
}
Just do String str = System.out.printf("%.2f", val).replace(",", "."); if you want to ensure that independently of the Locale of the user, you will always get / display a "." as decimal separator. This is a must if you don't want to make your program crash if you later do some kind of conversion like float f = Float.parseFloat(str);
Try this:-
private static String getDecimalFormat(double value) {
String getValue = String.valueOf(value).split("[.]")[1];
if (getValue.length() == 1) {
return String.valueOf(value).split("[.]")[0] +
"."+ getValue.substring(0, 1) +
String.format("%0"+1+"d", 0);
} else {
return String.valueOf(value).split("[.]")[0]
+"." + getValue.substring(0, 2);
}
}
Related
I want to print a double value in Java without exponential form.
double dexp = 12345678;
System.out.println("dexp: "+dexp);
It shows this E notation: 1.2345678E7.
I want it to print it like this: 12345678
What is the best way to prevent this?
Java prevent E notation in a double:
Five different ways to convert a double to a normal number:
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Runner {
public static void main(String[] args) {
double myvalue = 0.00000021d;
//Option 1 Print bare double.
System.out.println(myvalue);
//Option2, use decimalFormat.
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
System.out.println(df.format(myvalue));
//Option 3, use printf.
System.out.printf("%.9f", myvalue);
System.out.println();
//Option 4, convert toBigDecimal and ask for toPlainString().
System.out.print(new BigDecimal(myvalue).toPlainString());
System.out.println();
//Option 5, String.format
System.out.println(String.format("%.12f", myvalue));
}
}
This program prints:
2.1E-7
.00000021
0.000000210
0.000000210000000000000001085015324114868562332958390470594167709350585
0.000000210000
Which are all the same value.
Protip: If you are confused as to why those random digits appear beyond a certain threshold in the double value, this video explains: computerphile why does 0.1+0.2 equal 0.30000000000001?
http://youtube.com/watch?v=PZRI1IfStY0
You could use printf() with %f:
double dexp = 12345678;
System.out.printf("dexp: %f\n", dexp);
This will print dexp: 12345678.000000. If you don't want the fractional part, use
System.out.printf("dexp: %.0f\n", dexp);
0 in %.0f means 0 places in fractional part i.e no fractional part. If you want to print fractional part with desired number of decimal places then instead of 0 just provide the number like this %.8f. By default fractional part is printed up to 6 decimal places.
This uses the format specifier language explained in the documentation.
The default toString() format used in your original code is spelled out here.
In short:
If you want to get rid of trailing zeros and Locale problems, then you should use:
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:
Why other answers did not suit me:
Double.toString() or System.out.println or FloatingDecimal.toJavaFormatString uses scientific notations if double is less than 10^-3 or greater than or equal to 10^7
By using %f, the default decimal precision is 6, otherwise you can hardcode it, but it results in extra zeros added if you have fewer decimals. Example:
double myValue = 0.00000021d;
String.format("%.12f", myvalue); // Output: 0.000000210000
By using setMaximumFractionDigits(0); or %.0f you remove any decimal precision, which is fine for integers/longs, but not for double:
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
By using DecimalFormat, you are local dependent. In French locale, the decimal separator is a comma, not a point:
double myValue = 0.00000021d;
DecimalFormat df = new DecimalFormat("0");
df.setMaximumFractionDigits(340);
System.out.println(df.format(myvalue)); // Output: 0,00000021
Using the ENGLISH locale makes sure you get a point for decimal separator, wherever your program will run.
Why using 340 then for setMaximumFractionDigits?
Two reasons:
setMaximumFractionDigits accepts an integer, but its implementation has a maximum digits allowed of DecimalFormat.DOUBLE_FRACTION_DIGITS which equals 340
Double.MIN_VALUE = 4.9E-324 so with 340 digits you are sure not to round your double and lose precision.
You can try it with DecimalFormat. With this class you are very flexible in parsing your numbers.
You can exactly set the pattern you want to use.
In your case for example:
double test = 12345678;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(0);
System.out.println(df.format(test)); //12345678
I've got another solution involving BigDecimal's toPlainString(), but this time using the String-constructor, which is recommended in the javadoc:
this constructor is compatible with the values returned by Float.toString and Double.toString. This is generally the preferred way to convert a float or double into a BigDecimal, as it doesn't suffer from the unpredictability of the BigDecimal(double) constructor.
It looks like this in its shortest form:
return new BigDecimal(myDouble.toString()).stripTrailingZeros().toPlainString();
NaN and infinite values have to be checked extra, so looks like this in its complete form:
public static String doubleToString(Double d) {
if (d == null)
return null;
if (d.isNaN() || d.isInfinite())
return d.toString();
return new BigDecimal(d.toString()).stripTrailingZeros().toPlainString();
}
This can also be copied/pasted to work nicely with Float.
For Java 7 and below, this results in "0.0" for any zero-valued Doubles, so you would need to add:
if (d.doubleValue() == 0)
return "0";
Java/Kotlin compiler converts any value greater than 9999999 (greater than or equal to 10 million) to scientific notation ie. Epsilion notation.
Ex: 12345678 is converted to 1.2345678E7
Use this code to avoid automatic conversion to scientific notation:
fun setTotalSalesValue(String total) {
var valueWithoutEpsilon = total.toBigDecimal()
/* Set the converted value to your android text view using setText() function */
salesTextView.setText( valueWithoutEpsilon.toPlainString() )
}
This will work as long as your number is a whole number:
double dnexp = 12345678;
System.out.println("dexp: " + (long)dexp);
If the double variable has precision after the decimal point it will truncate it.
I needed to convert some double to currency values and found that most of the solutions were OK, but not for me.
The DecimalFormat was eventually the way for me, so here is what I've done:
public String foo(double value) //Got here 6.743240136E7 or something..
{
DecimalFormat formatter;
if(value - (int)value > 0.0)
formatter = new DecimalFormat("0.00"); // Here you can also deal with rounding if you wish..
else
formatter = new DecimalFormat("0");
return formatter.format(value);
}
As you can see, if the number is natural I get - say - 20000000 instead of 2E7 (etc.) - without any decimal point.
And if it's decimal, I get only two decimal digits.
I think everyone had the right idea, but all answers were not straightforward.
I can see this being a very useful piece of code. Here is a snippet of what will work:
System.out.println(String.format("%.8f", EnterYourDoubleVariableHere));
the ".8" is where you set the number of decimal places you would like to show.
I am using Eclipse and it worked no problem.
Hope this was helpful. I would appreciate any feedback!
The following code detects if the provided number is presented in scientific notation. If so it is represented in normal presentation with a maximum of '25' digits.
static String convertFromScientificNotation(double number) {
// Check if in scientific notation
if (String.valueOf(number).toLowerCase().contains("e")) {
System.out.println("The scientific notation number'"
+ number
+ "' detected, it will be converted to normal representation with 25 maximum fraction digits.");
NumberFormat formatter = new DecimalFormat();
formatter.setMaximumFractionDigits(25);
return formatter.format(number);
} else
return String.valueOf(number);
}
This may be a tangent.... but if you need to put a numerical value as an integer (that is too big to be an integer) into a serializer (JSON, etc.) then you probably want "BigInterger"
Example:
value is a string - 7515904334
We need to represent it as a numerical in a Json message:
{
"contact_phone":"800220-3333",
"servicer_id":7515904334,
"servicer_name":"SOME CORPORATION"
}
We can't print it or we'll get this:
{
"contact_phone":"800220-3333",
"servicer_id":"7515904334",
"servicer_name":"SOME CORPORATION"
}
Adding the value to the node like this produces the desired outcome:
BigInteger.valueOf(Long.parseLong(value, 10))
I'm not sure this is really on-topic, but since this question was my top hit when I searched for my solution, I thought I would share here for the benefit of others, lie me, who search poorly. :D
use String.format ("%.0f", number)
%.0f for zero decimal
String numSring = String.format ("%.0f", firstNumber);
System.out.println(numString);
I had this same problem in my production code when I was using it as a string input to a math.Eval() function which takes a string like "x + 20 / 50"
I looked at hundreds of articles... In the end I went with this because of the speed. And because the Eval function was going to convert it back into its own number format eventually and math.Eval() didn't support the trailing E-07 that other methods returned, and anything over 5 dp was too much detail for my application anyway.
This is now used in production code for an application that has 1,000+ users...
double value = 0.0002111d;
String s = Double.toString(((int)(value * 100000.0d))/100000.0d); // Round to 5 dp
s display as: 0.00021
This will work not only for a whole numbers:
double dexp = 12345678.12345678;
BigDecimal bigDecimal = new BigDecimal(Double.toString(dexp));
System.out.println("dexp: "+ bigDecimal.toPlainString());
My solution:
String str = String.format ("%.0f", yourDouble);
For integer values represented by a double, you can use this code, which is much faster than the other solutions.
public static String doubleToString(final double d) {
// check for integer, also see https://stackoverflow.com/a/9898613/868941 and
// https://github.com/google/guava/blob/master/guava/src/com/google/common/math/DoubleMath.java
if (isMathematicalInteger(d)) {
return Long.toString((long)d);
} else {
// or use any of the solutions provided by others, this is the best
DecimalFormat df =
new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
return df.format(d);
}
}
// Java 8+
public static boolean isMathematicalInteger(final double d) {
return StrictMath.rint(d) == d && Double.isFinite(d);
}
This works for me. The output will be a String.
String.format("%.12f", myvalue);
Good way to convert scientific e notation
String.valueOf(YourDoubleValue.longValue())
Can I do it with System.out.print?
You can use the printf method, like so:
System.out.printf("%.2f", val);
In short, the %.2f syntax tells Java to return your variable (val) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
There are other conversion characters you can use besides f:
d: decimal integer
o: octal integer
e: floating-point in scientific notation
You can use DecimalFormat. One way to use it:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));
Another one is to construct it using the #.## format.
I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.
I would suggest using String.format() if you need the value as a String in your code.
For example, you can use String.format() in the following way:
float myFloat = 2.001f;
String formattedString = String.format("%.02f", myFloat);
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
float f = 102.236569f;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24
You may use this quick codes below that changed itself at the end. Add how many zeros as refers to after the point
float y1 = 0.123456789;
DecimalFormat df = new DecimalFormat("#.00");
y1 = Float.valueOf(df.format(y1));
The variable y1 was equals to 0.123456789 before. After the code it turns into 0.12 only.
float floatValue=22.34555f;
System.out.print(String.format("%.2f", floatValue));
Output is 22.35.
If you need 3 decimal points change it to "%.3f".
Many people have mentioned DecimalFormat. But you can also use printf if you have a recent version of Java:
System.out.printf("%1.2f", 3.14159D);
See the docs on the Formatter for more information about the printf format string.
A simple trick is to generate a shorter version of your variable by multiplying it with e.g. 100, rounding it and dividing it by 100.0 again. This way you generate a variable, with 2 decimal places:
double new_variable = Math.round(old_variable*100) / 100.0;
This "cheap trick" was always good enough for me, and works in any language (I am not a Java person, just learning it).
Look at DecimalFormat
Here is an example from the tutorial:
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
If you choose a pattern like "###.##", you will get two decimal places, and I think that the values are rounded up. You will want to look at the link to get the exact format you want (e.g., whether you want trailing zeros)
To print a float up to 2 decimal places in Java:
float f = (float)11/3;
System.out.print(String.format("%.2f",f));
OUTPUT: 3.67
> use %.3f for up to three decimal places.
Below is code how you can display an output of float data with 2 decimal places in Java:
float ratingValue = 52.98929821f;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsFR = Float.valueOf(decimalFormat.format(ratingValue)); // output is 52.98
OK - str to float.
package test;
import java.text.DecimalFormat;
public class TestPtz {
public static void main(String[] args) {
String preset0 = "0.09,0.20,0.09,0.07";
String[] thisto = preset0.split(",");
float a = (Float.valueOf(thisto[0])).floatValue();
System.out.println("[Original]: " + a);
a = (float) (a + 0.01);
// Part 1 - for display / debug
System.out.printf("[Local]: %.2f \n", a);
// Part 2 - when value requires to be send as it is
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
System.out.println("[Remote]: " + df.format(a));
}
}
Output:
run:
[Original]: 0.09
[Local]: 0.10
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)
One issue that had me for an hour or more, on DecimalFormat- It handles double and float inputs differently. Even change of RoundingMode did not help. I am no expert but thought it may help someone like me. Ended up using Math.round instead.
See below:
DecimalFormat df = new DecimalFormat("#.##");
double d = 0.7750;
System.out.println(" Double 0.7750 -> " +Double.valueOf(df.format(d)));
float f = 0.7750f;
System.out.println(" Float 0.7750f -> "+Float.valueOf(df.format(f)));
// change the RoundingMode
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(" Rounding Up Double 0.7750 -> " +Double.valueOf(df.format(d)));
System.out.println(" Rounding Up Float 0.7750f -> " +Float.valueOf(df.format(f)));
Output:
Double 0.7750 -> 0.78
Float 0.7750f -> 0.77
Rounding Up Double 0.7750 -> 0.78
Rounding Up Float 0.7750f -> 0.77
public String getDecimalNumber(String number) {
Double d=Double.parseDouble(number);
return String.format("%.5f", d);
}
Take care of NumberFormatException as well
small simple program for demonstration:
import java.io.*;
import java.util.Scanner;
public class twovalues {
public static void main(String args[]) {
float a,b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Values For Calculation");
a=sc.nextFloat();
b=sc.nextFloat();
float c=a/b;
System.out.printf("%.2f",c);
}
}
Just do String str = System.out.printf("%.2f", val).replace(",", "."); if you want to ensure that independently of the Locale of the user, you will always get / display a "." as decimal separator. This is a must if you don't want to make your program crash if you later do some kind of conversion like float f = Float.parseFloat(str);
Try this:-
private static String getDecimalFormat(double value) {
String getValue = String.valueOf(value).split("[.]")[1];
if (getValue.length() == 1) {
return String.valueOf(value).split("[.]")[0] +
"."+ getValue.substring(0, 1) +
String.format("%0"+1+"d", 0);
} else {
return String.valueOf(value).split("[.]")[0]
+"." + getValue.substring(0, 2);
}
}
I have tried the following code but it is not working in a particular case.
Eg: Suppose, I have a double value=2.5045 and i want it to be rounded off upto two decimal places using the below code.After rounding off, i get the answer as 2.5. But I want the answer to be 2.50 instead. In this case,zero is trimmed off. Is there any way to retain the zero so as to get the desired answer as 2.50 after rounding off.
private static DecimalFormat twoDForm = new DecimalFormat("#.##");
public static double roundTwoDecimals(double amount) {
return Double.valueOf(twoDForm.format(amount));
}
try this pattern
new DecimalFormat("0.00");
but this will change only formatting, double cannot hold number of digits after decimal poin, try BigDecimal
BigDecimal bd = new BigDecimal(2.5045).setScale(2, RoundingMode.HALF_UP);
Look at the documentation for DecimalFormat. For # it says:
Digit, zero shows as absent
0 is probably what you want:
Digit
So what you are looking for is either "0.00" or "#.00" as a format string, depending on whether you want the first digit before the period, to be visible in case the numbers absolute value is smalle than 0.
Try this
DecimalFormat format = new DecimalFormat("#");
format.setMinimumFractionDigits(2);
answer.setText(format.format(data2));
Try This
double d = 4.85999999999;
long l = (int)Math.round(d * 100); // truncates
d = l / 100.0;
You are returning a double. But double or Double are objects representing a number and don't carry any formatting information. Ìf you need to output two decimal places the point to do this is when you convert your double to a String.
use # if you want to ignore 0
new DecimalFormat("###,#0.00").format(d)
There is another way to achieve this . I have already posted answer in post
will just answer again here. As we will require rounding off values many times .
public class RoundingNumbers {
public static void main(String args[]){
double number = 2.5045;
int decimalsToConsider = 2;
BigDecimal bigDecimal = new BigDecimal(number);
BigDecimal roundedWithScale = bigDecimal.setScale(decimalsToConsider, BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with setting scale = "+roundedWithScale);
bigDecimal = new BigDecimal(number);
BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with Dividing by one = "+roundedValueWithDivideLogic);
}
}
Output we will get is
Rounded value with setting scale = 2.50
Rounded value with Dividing by one = 2.50
double kilobytes = 1205.6358;
double newKB = Math.round(kilobytes*100.0)/100.0;
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("kilobytes (DecimalFormat) : " + df.format(kilobytes));
Try this if u are still getting the above problem
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 3 years ago.
This is what I did to round a double to 2 decimal places:
amount = roundTwoDecimals(amount);
public double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
This works great if the amount = 25.3569 or something like that, but if the amount = 25.00 or the amount = 25.0, then I get 25.0! What I want is both rounding as well as formatting to 2 decimal places.
Just use: (easy as pie)
double number = 651.5176515121351;
number = Math.round(number * 100);
number = number/100;
The output will be 651.52
Are you working with money? Creating a String and then converting it back is pretty loopy.
Use BigDecimal. This has been discussed quite extensively. You should have a Money class and the amount should be a BigDecimal.
Even if you're not working with money, consider BigDecimal.
Use a digit place holder (0), as with '#' trailing/leading zeros show as absent:
DecimalFormat twoDForm = new DecimalFormat("#.00");
Use this
String.format("%.2f", doubleValue) // change 2, according to your requirement.
You can't 'round a double to [any number of] decimal places', because doubles don't have decimal places. You can convert a double to a base-10 String with N decimal places, because base-10 does have decimal places, but when you convert it back you are back in double-land, with binary fractional places.
This is the simplest i could make it but it gets the job done a lot easier than most examples ive seen.
double total = 1.4563;
total = Math.round(total * 100);
System.out.println(total / 100);
The result is 1.46.
You can use org.apache.commons.math.util.MathUtils from apache common
double round = MathUtils.round(double1, 2, BigDecimal.ROUND_HALF_DOWN);
double amount = 25.00;
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(amount));
You can use Apache Commons Math:
Precision.round(double x, int scale)
source: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html#round(double,%20int)
Your Money class could be represented as a subclass of Long or having a member representing the money value as a native long. Then when assigning values to your money instantiations, you will always be storing values that are actually REAL money values. You simply output your Money object (via your Money's overridden toString() method) with the appropriate formatting. e.g $1.25 in a Money object's internal representation is 125. You represent the money as cents, or pence or whatever the minimum denomination in the currency you are sealing with is ... then format it on output. No you can NEVER store an 'illegal' money value, like say $1.257.
Starting java 1.8 you can do more with lambda expressions & checks for null. Also, one below can handle Float or Double & variable number of decimal points (including 2 :-)).
public static Double round(Number src, int decimalPlaces) {
return Optional.ofNullable(src)
.map(Number::doubleValue)
.map(BigDecimal::new)
.map(dbl -> dbl.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP))
.map(BigDecimal::doubleValue)
.orElse(null);
}
You can try this one:
public static String getRoundedValue(Double value, String format) {
DecimalFormat df;
if(format == null)
df = new DecimalFormat("#.00");
else
df = new DecimalFormat(format);
return df.format(value);
}
or
public static double roundDoubleValue(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);
First declare a object of DecimalFormat class. Note the argument inside the DecimalFormat is #.00 which means exactly 2 decimal places of rounding off.
private static DecimalFormat df2 = new DecimalFormat("#.00");
Now, apply the format to your double value:
double input = 32.123456;
System.out.println("double : " + df2.format(input)); // Output: 32.12
Note in case of double input = 32.1;
Then the output would be 32.10 and so on.
If you want the result to two decimal places you can do
// assuming you want to round to Infinity.
double tip = (long) (amount * percent + 0.5) / 100.0;
This result is not precise but Double.toString(double) will correct for this and print one to two decimal places. However as soon as you perform another calculation, you can get a result which will not be implicitly rounded. ;)
Math.round is one answer,
public class Util {
public static Double formatDouble(Double valueToFormat) {
long rounded = Math.round(valueToFormat*100);
return rounded/100.0;
}
}
Test in Spock,Groovy
void "test double format"(){
given:
Double performance = 0.6666666666666666
when:
Double formattedPerformance = Util.formatDouble(performance)
println "######################## formatted ######################### => ${formattedPerformance}"
then:
0.67 == formattedPerformance
}
Presuming the amount could be positive as well as negative, rounding to two decimal places may use the following piece of code snippet.
amount = roundTwoDecimals(amount);
public double roundTwoDecimals(double d) {
if (d < 0)
d -= 0.005;
else if (d > 0)
d += 0.005;
return (double)((long)(d * 100.0))/100);
}
where num is the double number
Integer 2 denotes the number of decimal places that we want to print.
Here we are taking 2 decimal palces
System.out.printf("%.2f",num);
Here is an easy way that guarantee to output the myFixedNumber rounded to two decimal places:
import java.text.DecimalFormat;
public class TwoDecimalPlaces {
static double myFixedNumber = 98765.4321;
public static void main(String[] args) {
System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
}
}
The result is: 98765.43
int i = 180;
int j = 1;
double div= ((double)(j*100)/i);
DecimalFormat df = new DecimalFormat("#.00"); // simple way to format till any deciaml points
System.out.println(div);
System.out.println(df.format(div));
You can use this function.
import org.apache.commons.lang.StringUtils;
public static double roundToDecimals(double number, int c)
{
String rightPad = StringUtils.rightPad("1", c+1, "0");
int decimalPoint = Integer.parseInt(rightPad);
number = Math.round(number * decimalPoint);
return number/decimalPoint;
}
need to round my answer to nearest10th.
double finalPrice = everyMile + 2.8;
DecimalFormat fmt = new DecimalFormat("0.00");
this.answerField.setText("£" + fmt.format(finalPrice) + " Approx");
the above code rounds a whole number to the nearest 10th however it wont round a decimal. e.g 2.44 should be rounded to 2.40
Use BigDecimal instead.
You really, really don't want to use binary floating point for monetary values.
EDIT: round() doesn't let you specify the decimal places, only the significant figures. Here's a somewhat fiddly technique, but it works (assuming you want to truncate, basically):
import java.math.*;
public class Test
{
public static void main(String[] args)
{
BigDecimal bd = new BigDecimal("20.44");
bd = bd.movePointRight(1);
BigInteger floor = bd.toBigInteger();
bd = new BigDecimal(floor).movePointLeft(1);
System.out.println(bd);
}
}
I'd like to hope there's a simpler way of doing this...
Change a bit the pattern to hard-code the final zero:
double finalPrice = 2.46;
DecimalFormat fmt = new DecimalFormat("0.0'0'");
System.out.println("£" + fmt.format(finalPrice) + " Approx");
Now, if you're manipulating real-world money, you'd better not use double, but int or BigInteger.
This outputs 2.40
BigDecimal bd = new BigDecimal(2.44);
System.out.println(bd.setScale(1,RoundingMode.HALF_UP).setScale(2));
Try the following:
double finalPriceRoundedToNearestTenth = Math.round(10.0 * finalPrice) / 10.0;
EDIT
Try this:
double d = 25.642;
String s = String.format("£ %.2f", Double.parseDouble(String.format("%.1f", d).replace(',', '.')));
System.out.println(s);
I know this is a stupid way, but it works.