Parse "45,978" to double value - java

I want to parse "45,978" to double which is read from a *.csv. Right now I am doing:
double P_current = Double.parseDouble(priceList.get(j));
However I am getting a number format exception for this string input:
java.lang.NumberFormatException: For input string: "45,978"
I know that I could change all the , in my csv file to a . which would probably work. However I do not want that, because I need the comma in this file. Is there any ways to parse this to double as-it-is?
I appreciate your answer!

If you don't want to replace anything, you can use Number and NumberFormat with Locale#GERMAN:
try {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
double number = nf.parse("45,978").doubleValue();
} catch(ParseException e) { }
If you want to be locale-independent, you can simply replace , with . to get the format that Double#parseDouble works with.

You should use the appropriate NumberFormat according to your locale :
NumberFormat format = NumberFormat.getInstance(Locale.GERMAN);
Number number = format.parse("45,978");
double d = number.doubleValue();

double parsed = Double.parseDouble(priceList.get(j).replace(',', '.'));
Or you could also use a DecimalFormat with the appropriate locale or symbols.

If your numbers are not from the English locale. Change the locale to a proper one:
NumberFormat format = NumberFormat.getInstance(Locale.FRENCH);
Number number = format.parse("45,978");
double d = number.doubleValue();
See more on NumberFormat here.

Related

How to Convert String value into Double or Int value in Java?

I have a problem. I have String with the value "$615.00" and I want to convert it to double or int.
I have tried the following code but there is an error:
String one = "$615.00";
String two = "$15.00";
double newone = Double.parseDouble( one );
double newtwo = Double.parseDouble( two );
System.out.println(newone-newtwo);
The error is
Exception in thread "main" java.lang.NumberFormatException: For input string: "$615.00"
But I have added the NumberFormatException for the method and still got the error.
As others have said in the comments, NumberFormatException is happening because you are trying to parseDouble without removing the $ from the number.
In this case, you can use substring() to get everything after the first char:
String one = "$615.00";
String two = "$15.00";
double newone = Double.parseDouble( one.substring(1) );
double newtwo = Double.parseDouble( two.substring(1) );
System.out.println(newone-newtwo);
Results in 600.00
$ is a currency designator. It is not part of a numeric value.
If you have a currency value, you should use a currency format to read it:
NumberFormat format = NumberFormat.getCurrencyInstance();
double newone = format.parse(one).doubleValue();
double newtwo = format.parse(two).doubleValue();
If you are not running on a computer configured for the US, you may need to pass a Locale, to force the currency instance to use US dollars:
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
double newone = format.parse(one).doubleValue();
double newtwo = format.parse(two).doubleValue();
Use regular expression to remove symbols like "$" (in other words, all symbols but digits and dot)
String one = "$615.03";
String oneValue = one.replaceAll("[^0-9.]", "");
System.out.println(oneValue); // Output is 615.03, which is correctly parsed by parseDobule()

Java - Format a String to show a pound sign and a decimal with two leading zeroes using objects and the toString method?

I have tried
System.out.println(myLorry.toString(registration, myCar.calcCharge()));
which outputs
Registration: TA17 NDD Charge: 7.0
I want my program to output
Registration: TA17 NDD Charge: £7.00
How can I format this correctly?
EDIT:
Why doesn't formatting work correctly? It says it's expecting two parameters but can only find one. I need to call objects using the toString method.
System.out.printf("%s £%.2f" ,myCar.toString(registration, myCar.calcCharge()));
like #davidxxx suggest in comment you can use
DecimalFormat d = new DecimalFormat("'£'0.00");
System.out.println(d.format(7.0));
Output
£7,00
If you have a problem with dot(.) and comma(,) then you can use DecimalFormatSymbols :
DecimalFormat d = new DecimalFormat("'£'0.00");
DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance();
sym.setDecimalSeparator('.');
d.setDecimalFormatSymbols(sym);
one solution is to use the printf.
e.g.
double value = 7.0;
System.out.printf("%s%.2f","£", value);
output:
£7.00
In fact you should consider two things :
formatting the number value with the fixed number of digits for the floating part.
setting the decimal separator character.
The second point may matter as according to the locale set by the JVM, you could get a distinct result : £7.00 or £7,00
So, you could specify the "£0.00" pattern in DecimalFormat and create the DecimalFormat instance with a specific DecimalFormatSymbols that ensures that you will use as decimal symbol the . character.
You could do it for example :
float f = 7;
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
otherSymbols.setDecimalSeparator('.');
NumberFormat formatter = new DecimalFormat("£0.00", otherSymbols);
String valueFormated = formatter.format(f);
But in fact a more simple way would be to use the String.format() method by specifying both the expected pattern (two digits for the floating part) and a Locale that uses the . as decimal separator :
float f = 7;
String valueFormated = String.format(Locale.US, "£%.2f", f);
Solved it! I was looking in completely the wrong part of my program, here is my solution:
String toString(String rn, double calcCharge)
{
DecimalFormat d = new DecimalFormat("£0.00");
return "Registration: " + rn + " Charge: " + d.format(calcCharge());
}
I had to modify a class that my subclasses inherited from.

Java - Convert a string to double with 10 or more decimals

How do I convert a string such as 40,123.012345678901 to a double?
double d = Double.parseDouble("40,123.012345678901");
throws a number format exception.
Thanks
If there is no way to get rid of comma(,) you may use another approach:
NumberFormat format = NumberFormat.getInstance(Locale.US);
Number number = format.parse("40,123.012345678901");
double d = number.doubleValue();
The simplest way is to remove comma:
double d = Double.parseDouble("40,123.012345678901".replace(",", ""));
A double is limited to around 16 digits of precision. If you need more precision, you should use BigDecimal.
BigDecimal bd = new BigDecimal("40,123.012345678901".replace(",", ""));
You should remove the comma (,) from your string:
This will work:
double d = Double.parseDouble("40123.012345678901");
Use NumberFormat to get double value,
try {
NumberFormat format = NumberFormat.getInstance();
Number parse = format.parse("40,123.012345678901");
System.out.println(parse.doubleValue());
} catch (ParseException ex) {
System.out.println(ex.getMessage());
}

Convert String to Number with Format

I was wondering if there is an existing method to convert a formatted number String to number, such as "123,456.78" to 123456.78
Basically, unlike DecimalFormat function, which turns a double variable to a String following that a given format such as "###,###.##" pattern. I want to implement a reverse of this functionality, which turns a String with "###,###.##" format to a double. Is there APIs to do this?
Thank you.
You should have looked through the documentation for DecimalFormat and its superclass. You would have discovered that it has not only format methods, but also parse methods like this one.
The easiest way to do what you want is:
NumberFormat format = NumberFormat.getInstance();
Number value = format.parse(string);
// If you specifically want a double...
double d = value.doubleValue();
You will have to catch ParseException and deal with it. How you do that depends on what you want to do when your string does not represent a valid numeric value. If it's user input, you may want to ask the user to enter the text again.
Here is a simple way to do this
String number = "20,000,000";
int x = Integer.parseInt(number.replace(",", ""));
System.out.println(x);
You just replace the char's that not belong to a number with "" and then parse it into a primitive.
String number = "20,000,000.56";
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(5);
double x = Double.parseDouble(number.replace(",", ""));
System.out.println(df.format(x));
It is a bit different for a Double cause it will display the exponential output and you'll have to prevent that. The code above does that.
df.format(x)
Returns a String but you can cast it with the Double.parseDouble method
Here's a method using a Regex and the replace method if you have more than one delimiter and you know them all :
Let's say the delimiters here are "-" and ","
double x = Double.parseDouble(number.replace("[-,]", "");

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.

Categories

Resources