Java: double: how to ALWAYS show two decimal digits - java

I use double values in my project and I would like to always show the first two decimal digits, even if them are zeros. I use this function for rounding and if the value I print is 3.47233322 it (correctly) prints 3.47. But when I print, for example, the value 2 it prints 2.0.
public static double round(double d) {
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
I want to print 2.00!
Is there a way to do this without using Strings?
EDIT: from your answers (which I thank you for) I understand that I wasn't clear in telling what I am searching (and I'm sorry for this): I know how to print two digits after the number using the solutions you proposed... what i want is to store in the double value directly the two digits! So that when I do something like this System.out.println("" + d) (where d is my double with value 2) it prints 2.00.
I'm starting to think that there is no way to do this... right? Thank you again anyway for your answers, please let me know if you know a solution!

You can use something like this:
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.00");
System.out.print(df.format(d));
Edited to actually answer the question because I needed the real answer and this came up on google and someone marked it as the answer despite the fact that this wasn't going to work when the decimals were 0.

Use the java.text.NumberFormat for this:
NumberFormat nf= NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
nf.setRoundingMode(RoundingMode.HALF_UP);
System.out.print(nf.format(decimalNumber));

You can simply do this:
double d = yourDoubleValue;
String formattedData = String.format("%.02f", d);

DecimalFormat is the easiest option to use:
double roundTwoDecimals(double d) {
DecimalFormat twoDecimals = new DecimalFormat("#.##");
return Double.valueOf(twoDecimals.format(d));
}
Hope this solves your issue...

java.text.DecimalFormat df = new java.text.DecimalFormat("###,###.##");
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);

You can use something like this:
If you want to retain 0 also in the answer:
then use (0.00) in the format String
double d = 2.46327;
DecimalFormat df = new DecimalFormat("0.00");
System.out.print(df.format(d));
The output: 2.46
double d = 0.0001;
DecimalFormat df = new DecimalFormat("0.00");
System.out.print(df.format(d));
The output: 0.00
However, if you use DecimalFormat df = new DecimalFormat("0.##");
double d = 2.46327;
DecimalFormat df = new DecimalFormat("0.##");
System.out.print(df.format(d));
The output: 2.46
double d = 0.0001;
DecimalFormat df = new DecimalFormat("0.##");
System.out.print(df.format(d));
The output: 0

I would just use something like:
System.out.printf("%.2f", theValueYouWantToPrint);
This gives you two decimals.

Related

How to get up to two decimal point for float? Ex- 25.00000

Floating point with more than a zero after the point is not showing up to two decimal point.
I've tried DecimalFormat to convert. It's worked for round up except(with more than a zero) ex- 25.00000
DecimalFormat df = new DecimalFormat("0.00");
df.setMinimumFractionDigits(2);
Double.parseDouble(df.format(frog_per));
I expect the output of 25.00000 to be 25.00, but the actual output is 25.0.
You can use String.format(String format, Object... args)
class Main {
public static void main(String[] args) {
System.out.println(String.format("%.2f",25.0000));
}
}
Output:
25.00
https://onlinegdb.com/BJ5W0ibKB
Kindly change DecimalFormat df = new DecimalFormat("0.00"); to DecimalFormat df = new DecimalFormat("#,###,##0.00");
Your format pattern 0.00 is fine.
Just don't construct the double out of the formatted string in order to display it as a formatted output.
Double object created from input 25.00 or 25.00000 or 25 is having the value of 25. It stores the value and never the formatting.
If you want this object to be used to produce 25.00 output you have to format it again, by using either method used in other answers:
Double d = 25.00000d;
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(d));
System.out.printf("%.2f", d);
produces expected output:
25.00
25.00
This is how u round off 2 decimals.
DecimalFormat df2 = new DecimalFormat(".##");
df2.format(variable)

How to add 0 to decimal instead of 12.5 it will be 12.50

public double calculateMPG() {
double a = (this.myEndMiles - this.myStartMiles);
return ((a) / (this.gallons));
}
How would I make this function spit out 12.50 instead of 12.5
Thanks
You cannot really make it return 12.50 instead of 12.5 because you are returning a double. Thus, it will be 12.5 . However, you can display it in that way. Here is how:
NumberFormat numFormat = new DecimalFormat("#.00");
System.out.println( numFormat.format(calculateMPG()) );
String.format("%.2f", calculateMPG());
Note that this produces a String representation of the formatted number.
The double itself makes no difference between 12.5 and 12.50 and 0012.500.
DecimalFormat df = new DecimalFormat("#.00");
Note the "00", meaning exactly two decimal places.
example
DecimalFormat formatter = new DecimalFormat("#0.00");
double d = 4.0;
System.out.println(formatter.format(d));

How to parse string to double with out scientific notation

I want to parse string to double but with scientific notation. Please provide ant solution for solving this problem.
String str="123434344";
Double db=Double.parseDouble(str);
System.out.println("Value:"+db);
This is my output:
Value:1.23434344E8
but i want to this double like this: 123434344.00
How it is possible please provide me solution for this. Thanks a lot.!!
String str="123434344";
Double db=Double.parseDouble(str);
DecimalFormat format = new DecimalFormat("0.00");
System.out.println("Value:"+format.format(db));
You could use :
DecimalFormat df = new DecimalFormat("0.00");
Double d = Double.parseDouble("123434344");
System.out.println(df.format(d));
The output will be :
123434344.00
System.out.printf("Value: %0.2f%n", db);
Print formated, Where %n stands for newline.

Double decimal formatting in Java

I'm having some problems formatting the decimals of a double. If I have a double value, e.g. 4.0, how do I format the decimals so that it's 4.00 instead?
One of the way would be using NumberFormat.
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(4.0));
Output:
4.00
With Java 8, you can use format method..: -
System.out.format("%.2f", 4.0); // OR
System.out.printf("%.2f", 4.0);
f is used for floating point value..
2 after decimal denotes, number of decimal places after .
For most Java versions, you can use DecimalFormat: -
DecimalFormat formatter = new DecimalFormat("#0.00");
double d = 4.0;
System.out.println(formatter.format(d));
Use String.format:
String.format("%.2f", 4.52135);
As per docs:
The locale always used is the one returned by Locale.getDefault().
Using String.format, you can do this:
double price = 52000;
String.format("$%,.2f", price);
Notice the comma which makes this different from #Vincent's answer
Output:
$52,000.00
A good resource for formatting is the official java page on the subject
You could always use the static method printf from System.out - you'd then implement the corresponding formatter; this saves heap space in which other examples required you to do.
Ex:
System.out.format("%.4f %n", 4.0);
System.out.printf("%.2f %n", 4.0);
Saves heap space which is a pretty big bonus, nonetheless I hold the opinion that this example is much more manageable than any other answer, especially since most programmers know the printf function from C (Java changes the function/method slightly though).
double d = 4.0;
DecimalFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
System.out.println(nf.format("#.##"));
You can use any one of the below methods
If you are using java.text.DecimalFormat
DecimalFormat decimalFormat = NumberFormat.getCurrencyInstance();
decimalFormat.setMinimumFractionDigits(2);
System.out.println(decimalFormat.format(4.0));
OR
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
System.out.println(decimalFormat.format(4.0));
If you want to convert it into simple string format
System.out.println(String.format("%.2f", 4.0));
All the above code will print 4.00
new DecimalFormat("#0.00").format(4.0d);
An alternative method is use the setMinimumFractionDigits method from the NumberFormat class.
Here you basically specify how many numbers you want to appear after the decimal point.
So an input of 4.0 would produce 4.00, assuming your specified amount was 2.
But, if your Double input contains more than the amount specified, it will take the minimum amount specified, then add one more digit rounded up/down
For example, 4.15465454 with a minimum amount of 2 specified will produce 4.155
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
Double myVal = 4.15465454;
System.out.println(nf.format(myVal));
Try it online
There are many way you can do this. Those are given bellow:
Suppose your original number is given bellow:
double number = 2354548.235;
Using NumberFormat:
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(number));
Using String.format:
System.out.println(String.format("%,.2f", number));
Using DecimalFormat and pattern:
NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
DecimalFormat decimalFormatter = (DecimalFormat) nf;
decimalFormatter.applyPattern("#,###,###.##");
String fString = decimalFormatter.format(number);
System.out.println(fString);
Using DecimalFormat and pattern
DecimalFormat decimalFormat = new DecimalFormat("############.##");
BigDecimal formattedOutput = new BigDecimal(decimalFormat.format(number));
System.out.println(formattedOutput);
In all cases the output will be:
2354548.23
Note:
During rounding you can add RoundingMode in your formatter. Here are some rounding mode given bellow:
decimalFormat.setRoundingMode(RoundingMode.CEILING);
decimalFormat.setRoundingMode(RoundingMode.FLOOR);
decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
decimalFormat.setRoundingMode(RoundingMode.UP);
Here are the imports:
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
Works 100%.
import java.text.DecimalFormat;
public class Formatting {
public static void main(String[] args) {
double value = 22.2323242434342;
// or value = Math.round(value*100) / 100.0;
System.out.println("this is before formatting: "+value);
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
}
}
First import NumberFormat. Then add this:
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
This will give you two decimal places and put a dollar sign if it's dealing with currency.
import java.text.NumberFormat;
public class Payroll
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
int hoursWorked = 80;
double hourlyPay = 15.52;
double grossPay = hoursWorked * hourlyPay;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
System.out.println("Your gross pay is " + currencyFormatter.format(grossPay));
}
}
You can do it as follows:
double d = 4.0;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
I know that this is an old topic, but If you really like to have the period instead of the comma, just save your result as X,00 into a String and then just simply change it for a period so you get the X.00
The simplest way is just to use replace.
String var = "X,00";
String newVar = var.replace(",",".");
The output will be the X.00 you wanted. Also to make it easy you can do it all at one and save it into a double variable:
Double var = Double.parseDouble(("X,00").replace(",",".");
I know that this reply is not useful right now but maybe someone that checks this forum will be looking for a quick solution like this.

Convert a number to 2 decimal places in Java

I want to convert a number to a 2 decimal places (Always show two decimal places) in runtime. I tried some code but it only does, as shown below
20.03034 >> 20.03
20.3 >> 20.3 ( my code only rounds not converts )
however, I want it to do this:
20.03034 >> 20.03
20.3 >> 20.30 (convert it to two decimal places)
My code below:
angle = a variable
angle_screen = a variable
DecimalFormat df = new DecimalFormat("#.##");
angle = Double.valueOf(df.format(angle));
angle_screen.setText(String.valueOf(angle) + tmp);
Any help on how to do this would be great, thanks.
try this new DecimalFormat("#.00");
update:
double angle = 20.3034;
DecimalFormat df = new DecimalFormat("#.00");
String angleFormated = df.format(angle);
System.out.println(angleFormated); //output 20.30
Your code wasn't using the decimalformat correctly
The 0 in the pattern means an obligatory digit, the # means optional digit.
update 2: check bellow answer
If you want 0.2677 formatted as 0.27 you should use new DecimalFormat("0.00"); otherwise it will be .27
DecimalFormat df=new DecimalFormat("0.00");
Use this code to get exact two decimal points.
Even if the value is 0.0 it will give u 0.00 as output.
Instead if you use:
DecimalFormat df=new DecimalFormat("#.00");
It wont convert 0.2659 into 0.27. You will get an answer like .27.
Try this: String.format("%.2f", angle);
Try
DecimalFormat df = new DecimalFormat("#,##0.00");

Categories