Convert String to Number with Format - java

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("[-,]", "");

Related

How to store a value greater than "999" in double while using parseDouble function?

I am not able to store value greater than "999" while using parseDouble function. This is my code:
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
double amount = Double.parseDouble(formatter.format(Double.parseDouble(balanceAmt.getText().toString())));
It is only storing value upto "999" not greater than that. It does not allow me to store value "1000" or greater.
Error message:
java.lang.NumberFormatException: For input string: "123,456.78"
The default method NumberFormat.format(String) automatically puts a comma separating thousands when setting it to formatted text. This comma can not be parsed into a double datatype because it only accepts '.' as the decimal split character and numbers around it.
This can be seen by this test:
double amount = Double.parseDouble(formatter.format(Double.parseDouble("1000")).replace(",", ""));
If the number requires a comma then use the .replace() method to replace it when parsing it to a double. Otherwise use a custom instantiation for your Number formatter such as:
NumberFormat formatter = new DecimalFormat("0000.00");
I am working under the assumption that balanceAmt.getText().toString() is returning 123,456.78 or similar.
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
double amount = Double.parseDouble(formatter.format(Double.parseDouble(balanceAmy.getText().toString().replace(",", ""))).replace(",", ""));
System.out.print(amount);
When you get the balance from balanceAmt, it has the comma, so you have to remove it. When if goes through the formatter, it re-adds the comma back, meaning you have to remove it again before the second parseDouble is done.

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.

Trimming text in java

is java have method to trimming text/string? like this one :
int comaNumber = input.nextInt();
string number = "234,56789";
int coma = number.indexOf(",");
string number = number.substring(0,coma(comaNumber+1));
note : it will search coma character and then it will trim the number based on amount of coma in comaNumber, the result is 234,56 (works)
is any method in java to trimming decimal number to simplify my works? (not trim() function)
Edit: the number of decimal place is specified by user input.
The easiest way is to use DecimalFormat. Although, to get that working with a comma you will need to modify the FormatSymbols.
It would be something like this:
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');//this tels DecimalFormat to use ',' as the decimal separator
String pattern = "#.00";//this means that you want only 2 decimals
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
System.out.println(decimalFormat.parse("221012,28").doubleValue());
System.out.println(decimalFormat.format(1234.123121));
That prints
221012.28
1234,12
You could try using String.format. First switch the comma with a period. For example,
number = number.replace(",",".");
double y = Double.parseDouble(number);
String x = String.format("%.2d",number);
x = x.replace(".",",");
First, you replace the comma with a period. Then you use the parseDouble method(documentation https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)). Then you use String.format to save it with only two places after the decimal point. Then change decimal back to comma.
Hope this helps!
As far as I know, there is no such method. My advice is to create your own method, and then reference it whenever you need it.

Convert to int from String of numbers having comma

I have value like this:
String x = "10,000";
I want to convert this to int.
I can convert it by removing comma like below:
String y = x.replace(",", "");
int value1 = Integer.parseInt(y);
But I don't want to do it like above.
Any other suggestions like inbuilt function? Or any other recommended ways for this?
You can simply:
NumberFormat.getNumberInstance(Locale.UK).parse(x);
Read about:
NumberFormat
Locale.UK and others.
Try this:
NumberFormat format = NumberFormat.getInstance(Locale.US);
Number number = format.parse("10,000");
// Now you can get number values from the object (like int, long, double)
System.out.println(number.intValue());
Output:
10000
Note: If you string contains values after decimal point, you need to use number.doubleValue to retain the precision because number.intValue() will simply ignore values after decimal points.
Use any one of these:
NumberFormat.getNumberInstance(Locale.ENGLISH).parse("10,000").intValue();
NumberFormat.getNumberInstance(Locale.US).parse("10,000").intValue();
NumberFormat.getNumberInstance(Locale.UK).parse("10,000").intValue();

Parse "45,978" to double value

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.

Categories

Resources