How to handle Measurement unit to string [duplicate] - 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.

Related

Java Convert string to double [duplicate]

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.

How to make a string from a BegDecimal number which contained only the integral part

My question is about of toString() and toPlainString() methods of the BigDecimal dataTypewhich produces the output like
750.0000
150.0000
... etc
My question is how to specify the number of zeros followed after the dot? Is there a way to do it instead of String.replace(".0000", ".00") method?
Use DecimalFormat in combination with DecimalFormatSymbols:
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
DecimalFormat df = new DecimalFormat("##.##");
df.setDecimalFormatSymbols(dfs);
df.format(myNumber)
Without using DecimalFormatSymbols you would end up with a comma as a decimal seperator instead.
Please use the below code.
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
String s = nf.format(1111.2222);
System.out.println(s);
Apart from decimal format you can also use setScale(2) like this
new BigDecimal("1.0000").setScale(2)
Also setScale allows you can specify the Rounding Mode
You could use setScale method and optinally you could choose rounding methodology of your own. Somethign like:
BigDecimal b = new BigDecimal("750.0000");
b.setScale(2);

How do you allow a double with multiple decimals to only show, NOT ROUND, one decimal [duplicate]

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.

Java DecimalFormat

DecimalFormat df2 = new DecimalFormat("#.##");
double zipf = 0.23951367781155017;
String zipt = df2.format(zipf);
System.out.println(zipt);
And I get "0,24"
The problem with this is then I want to use it as a double. But the Double.valueOf(); method fails due to the comma being there in the string output. Any way to solve this?
For decimal dot, you should create an instance with english locale like this:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
String zipt = nf.format(zipf);
System.out.println(zipt);
I also suggest setting rounding to HALF_UP, because default rounding is not what most of us would expect: http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html#ROUND_HALF_EVEN
nf.setRoundingMode(RoundingMode.HALF_UP);
Use different locale.German has dot
NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;
Alternative woud be to use string and then modify string to your needs.After that just parse to double.All done :)
Your problems is the local that your JVM is using , try to change at your current local.
Use DecimalFormat constructor that allows you to specify locale
new DecimalFormat("#.##", new DecimalFormatSymbols(new Locale("en")));
you could "format" your double manually but cutting of the decimal places like this:
DecimalFormat df2 = new DecimalFormat("#.##");
double zipf = 0.23951367781155017;
String zipt = df2.format(zipf);
System.out.println(zipt);
long zipfLong = Math.round(zipf*100);
double zipfDouble = zipfLong/100.0;
System.out.println(zipfDouble);
with Math.round you make sure the that 0.239.. becomes 0.24. zipf*100 will "cut" off the additional decimal places and zipfLong/100.0 will add the decimal places again. Sorry, bad explanation but here is the output:
0,24
0.24
And you can reuse the new zipfDouble as a double value without casting or taking care of locale settings.

How do I round a double that I've converted into a string in java?

Can someone please tell me why this doesn't work? I'm confident it's because i'm trying to format a string to two decimal places.. but i don't know how else to make the output rounded to decimal places.
DecimalFormat df = new DecimalFormat("#.##");
String sTotalCost = Double.toString(totalCost);
txtTotalCost.setText("£" + df.format(sTotalCost));
Don't convert it to a string before formatting:
DecimalFormat df = new DecimalFormat("#.##");
txtTotalCost.setText("£" + df.format(totalCost));
If you just like to round for displaying purpose (as String), you did it correct. Just set the Roundmode that fits for you:
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.HALF_EVEN);
txtTotalCost.setText("£" + df.format(totalCost));
See: DecimalFormat rounding
If you like to calculate on the rounded variable, you should round it like this:
double roundedTotalCost = Math.round(totalCost*100.0)/100.0
See: http://www.mkyong.com/java/how-to-round-double-float-value-to-2-decimal-points-in-java/

Categories

Resources