Formatting double to 2 decimals doesn't work - java

I want to round this double:
3.499999999999999
to:
3.50
And I already used these two methods:
DecimalFormat df = new DecimalFormat("0.00");
double result = Double.valueOf(df.format(input));
System.out.println(answer);
and
public double round(double input)
{
int decimalPlace = 2;
BigDecimal bd = new BigDecimal(input);
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_UP);
return (bd.doubleValue());
}
But It keeps printing:
3.5
Does anyone have a solution for this? Because I really think that this should work. Thanks for your help.

Your first solution is really, really close. Just do this:
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(input));
The reason your version doesn't work is that you're taking the input double, formatting it as a String with 2dp, but then converting it back to a double. System.out.println is then printing the double as it always would, with no special decimal-place rules.

You can use the printf formatting which may be simpler.
System.out.printf("%.2f%n", 3.5);
prints
3.50

Did you try replacing the 0's with #'s?
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(input));
According to here the # will be resolved to 0 if the digit is absent

You can use Precision class of apache commons-math
double result = Precision.round(3.499999999999999, 2);

Related

how to print precise floating double values

i want to print a double value like 0.000027,
but it's getting printed as 2.7340E-05.
i'm using-
editTextYARD.setText(String.format(Locale.US, "%6.4E"));
please help...
This will convert a given double value to show decimal point up to 7
double value = 0.0000027;
System.out.println(String.format("%.7f", (double)value));
you may use it like this
editTextYARD.setText(""+String.format("%.7f", (double)value));
You can use DecimalFormat for this purpose.
double myvalue = 1.2345678878;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(10);
your_editText.setText(df.format(myvalue));
When print to console:
System.out.printf( "%04.2f", var)
When print to string, I think ( I am not tried yet...)
This worth trying..
String ret = String.format ("%04.2f", var)

How to always round off upto 2 decimal places in java

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

Rounding off double value in Java

Currently I'm using DecimalFormat class to round off double value
double d = 42.405;
DecimalFormat f = new DecimalFormat("##.00");
System.out.println(f.format(d));
output: 42.41;
I'm doing browser app testing using Selenium, so based on the browser I need to round off the value.
For Example:
IE rounds off 42.405 to 42.40 and others rounds off to 42.41. But if values are like 42.403, 42.406 then I see consistency across all browsers. So now I have to put a condition in my script so if browser is IE then round off should happen in such a way that I should get 42.40 and for other browsers is should get 42.41. How can i do this?
You can specify the RoundingMode for the DecimalFormatter, but please choose it as per your needs(I've just given an example using HALF_UP).
double d = 42.405;
DecimalFormat f = new DecimalFormat("##.00");
f.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(f.format(d)); // Prints 42.41
Alternatively, you can also use BigDecimal(incase you know why we usually go for BigDecimal instead of double) for the same.
double d = 42.405;
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2, RoundingMode.HALF_UP);
System.out.println(bd.doubleValue()); // Prints 42.41
DecimalFormat f=new DecimalFormat("0.00");
String formate = f.format(value);
double finalValue = (Double)f.parse(formate) ;
System.out.println(finalValue);
Use setRoundingMode as:
f.setRoundingMode( RoundingMode.DOWN );
How to round a number to n decimal places in Java
try this may be helpful:
double d = 42.405;
System.out.println(String.format("%2.2f", d));
Also you can do it "handly" as follow
double d = 42.405;
final double roundedValue = (Math.round(d * 100) / (double) 100);
In case of 42.405 you get 42.41 and in case of 42.404 - 42.4
And so after
System.out.println(String.format("%2.2f", roundedValue));
you will get necessary output. 42.41 or 42.40 correspondingly.

Formatting a number with correct decimal scale

I need to format a number with scale of 2 decimal places. The original number may be a whole number or a number with three decimal places. However the result should be formatted to have commas and also two decimal places always regardless of whether the original number is whole number or having decimal places.
When original num = 56565656.342 ==> I need 56,565,656.34
When original num = 56565656 ==> I need 56,565,656.00
When original num = 56565656.7 ==> I need 56,565,656.70
I am using the following code which is formatting the code but its failing to add the two decimal places in the above 2 & 3 cases.
String originalNumber = "56565656.7";
BigDecimal b = new BigDecimal(originalNumber).setScale(2, BigDecimal.ROUND_HALF_UP);
String formattedNumber = NumberFormat.getInstance().format(b);
Please let me know if there is any way to accomplish this in efficeint way.
Thanks in advance.
Take a look at the DecimalFormat class.
Alternatively you can setScale method from the BigDecimal Class.
BigDecimal bg1 = new BigDecimal("56565656.342");
BigDecimal bg2 = new BigDecimal("56565656.00");
BigDecimal bg3 = new BigDecimal("56565656.70");
DecimalFormat df = new DecimalFormat("###,###.00");
System.out.println(df.format(bg1.doubleValue()));
System.out.println(df.format(bg2.doubleValue()));
System.out.println(df.format(bg3.doubleValue()));
System.out.println(bg1.setScale(2, BigDecimal.ROUND_HALF_UP));
System.out.println(bg2.setScale(2, BigDecimal.ROUND_HALF_UP));
System.out.println(bg3.setScale(2, BigDecimal.ROUND_HALF_UP));
Yields:
56,565,656.34
56,565,656.00
56,565,656.70
56565656.34
56565656.00
56565656.70
EDIT: Also forgot to mention: If you are after precision, I would recommend you use the setScale method, using the .doubleValue() method will yield a double which can cause loss of precision.
Just use NumberFormat and specify the fraction digits, and rounding method, to print :
String [] originalNumbers = new String[] {
"56565656.342",
"56565656.7",
"56565656"
};
NumberFormat df = NumberFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setRoundingMode(RoundingMode.HALF_UP);
for (String number : originalNumbers) {
String formattedNumber = df.format(new BigDecimal(number));
System.out.println(formattedNumber);
}
Will print
56,565,656.34
56,565,656.70
56,565,656.00
** Edit **
DecimalFormat df = new DecimalFormat("#,###.00");
Will produce the exact same result with the given code above.
DecimalFormat class would do it for you.... You will have to specify appropriate format.

DecimalFormat rounding

Here is small code to illustrate what I am seeing
float floater = 59.999f;
DecimalFormat df = new DecimalFormat("00.0");
System.out.println(df.format(floater));
This prints:
60.0
I would like it to print
59.9
What do I need to do?
Add this line before using the DecimalFormat:
df.setRoundingMode(RoundingMode.DOWN);
Take a look at the other rounding modes and see which one is best for you.
Note : this method works only in JDK 1.6 or above
float d = 59.999f;
BigDecimal bd = new BigDecimal(d);
// Use the returned value from setScale, as it doesn't modify the caller.
bd = bd.setScale(1, BigDecimal.ROUND_FLOOR);
String formatted = bd.toString();

Categories

Resources