Why does it not round in the parsing process?
NumberFormat format = NumberFormat.getInstance();
System.out.println(format.getMaximumFractionDigits());// 3
System.out.println(format.getRoundingMode());// half even
Double dob = (Double)format.parse("1212.35656");
System.out.println(dob);// output is 1212.35656
The digit counts are only used for formatting. When you parse a number you always get the number that best matches the input, even if it has more digits than the NumberFormat would use to format.
To parse a number from a string and then round to a given number of fractional digits you can use BigDecimal from the java.math package:
BigDecimal bd = BigDecimal("1212.35656");
double dob = bd.setScale(3, RoundingMode.HALF_EVEN).doubleValue();
To obtain what you desire you need to call the formatter metod of the implementation NumberFormat loaded (in your case DecimalFromat); i just added the needed lines at the end and wrapped in a main:
import java.text.NumberFormat;
public class NumberFormatRounding {
public static void main(String[] args) throws Exception{
NumberFormat formatter = NumberFormat.getInstance();
System.out.println(formatter.getMaximumFractionDigits());// 3
System.out.println(formatter.getRoundingMode());// half even
Double dob = (Double) formatter.parse("1212.35656");
System.out.println(dob);// output is 1212.35656
String formattedDob = formatter.format(dob.doubleValue());
System.out.println(formattedDob);// output is 1212.357
}
}
Note that the formattedDob is a String
Related
I'm trying to take a string and convert into a currency. For example I would like to take the string 12579500 and convert it to $125,795.00. I am trying to use DecimalFormat("$#,###.00), to convert the string after I turn it into a double, but what I'm winding up with is $12,579,500.00.
How do I set the last 2 numbers at the end of the string to be decimal points?
Here is my code so far.
DecimalFormat df = new DecimalFormat("$#,###.00");
double ticketPriceNum = Double.parseDouble(ticketPrice);
System.out.print(df.format(ticketPriceNum));
This will make sure that your string is reduced by 2 characters
DecimalFormat df = new DecimalFormat("$#,###.00");
double ticketPriceNum = Double.parseDouble(ticketPrice.substring(0, ticketPrice.length()- 2));
System.out.print(df.format(ticketPriceNum));
try this please
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("$#,###,##.00");
//if last two digits of ticketprice should be decimal points
double ticketPriceNum = Double.parseDouble(ticketPrice/100);
System.out.println(df.format(ticketPriceNum ));
}
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.
I am trying to figure out how to, given a decimal through a String calculate the number of significant digits so that I can do a calculation to the decimal and print the result with the same number of significant digits. Here's an SSCCE:
import java.text.DecimalFormat;
import java.text.ParseException;
public class Test {
public static void main(String[] args) {
try {
DecimalFormat df = new DecimalFormat();
String decimal1 = "54.60"; // Decimal is input as a string with a specific number of significant digits.
double d = df.parse(decimal1).doubleValue();
d = d * -1; // Multiply the decimal by -1 (this is why we parsed it, so we could do a calculatin).
System.out.println(df.format(d)); // I need to print this with the same # of significant digits.
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I know DecimalFormat is to 1) tell the program how you intend your decimal to be displayed (format()) and 2) to tell the program what format to expect a String-represented decimal to be in (parse()). But, is there a way to DEDUCE the DecimalFormat from a parsed string and then use that same DecimalFormat to output a number?
Use BigDecimal:
String decimal1 = "54.60";
BigDecimal bigDecimal = new BigDecimal(decimal1);
BigDecimal negative = bigDecimal.negate(); // negate keeps scale
System.out.println(negative);
Or the short version:
System.out.println((new BigDecimal(decimal1)).negate());
Find it via String.indexOf('.').
public int findDecimalPlaces (String input) {
int dot = input.indexOf('.');
if (dot < 0)
return 0;
return input.length() - dot - 1;
}
You can also configure a DecimalFormat/ NumberFormat via setMinimumFractionDigits() and setMaximumFractionDigits() to set an output format, rather than having to build the pattern as a string.
int sigFigs = decimal1.split("\\.")[1].length();
Computing the length of the string to the right of the decimal is probably the easiest method of achieving your goal.
If you want decimal places, you can't use floating-point in the first place, as FP doesn't have them: FP has binary places. Use BigDecimal, and construct it directly from the String. I don't see why you need a DecimalFormat object at all.
You could convert a number string to a format string using regex:
String format = num.replaceAll("^\\d*", "#").replaceAll("\\d", "0");
eg "123.45" --> "#.00" and "123" --> "#"
Then use the result as the pattern for a DecimalFormat
Not only does it work, it's only one line.
I am trying to format a Number with DecimalFormat. But I want it to format a number, that is like
input: 1234. --> should be formatted to: 1,234.
But I get 1,234.0 or 1,234.00 depending on my rules for the decimal format
What do I have to do in order to get this done?
The methods that should help you are setMinimumFractionDigits and setMaximumFractionDigits.
format.setMinimumFractionDigits(0);
at a guess, is probably what your looking for.
To ensure that the decimal separator is always shown, use: DecimalFormat.setDecimalSeparatorAlwaysShown(true)
You could format the number regardless of whether it is a decimal or not by using
DecimalFormat f = new DecimalFormat("#,###");
f.format(whatever)...
If you don't want to display any decimal places, don't format a floating point value :) If you use BigInteger, int, or long, it should be fine:
import java.math.*;
import java.text.*;
public class Test {
private static final char p = 'p';
public static void main(String[] args) {
NumberFormat format = new DecimalFormat();
BigInteger value = BigInteger.valueOf(1234);
System.out.println(format.format(value));
System.out.println(format.format(1234));
System.out.println(format.format(1234L));
}
}
Try this:
DecimalFormat df = new DecimalFormat("#,###.", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
System.out.println(df.format(1234));
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.