Get double value from currency frormatted string - java

I'm using NumberFormat in my app to get the currency formatted Strings. Like if a user inputs 12.25 in the field then it will be changed to $12.25 based on locale. Here the Locale is en-US.
Now I want to get the 12.25 value as double form the formatted string.
To do that I have used:
NumberFormat.getCurrencyInstance().parse("$12.25").doubleValue();
Above line giving me the result of 12.25 which is my requirement. But suppose a user changed his locale to something else en-UK. Now for that locale above statement is giving me parseException. Because for the locale en-UK, currency string $12.25 is not parsable.
So is there any way to get the double value from currency formatted string irrespective of what the locale is?

I don't know either the below solution is perfect or not but it is working according to my requirement.
try {
return NumberFormat.getCurrencyInstance().parse(currency).doubleValue();
} catch (ParseException e) {
e.printStackTrace();
// Currency string is not parsable
// might be different locale
String cleanString = currency.replaceAll("\\D", "");
try {
double money = Double.parseDouble(cleanString);
return money / 100;
} catch (Exception ex) {
ex.printStackTrace();
}
}
return 0;

What about
new Double(NumberFormat.getCurrencyInstance().parse("$12.25").doubleValue());
and also you could use
Double.valueOf() creates a Double object so .doubleValue() should not be necessary.
also Double.parseDouble(NumberFormat.getCurrencyInstance().parse("$12.25"));
could work

Here's a little algorithm that may help you :
public static void main(String[] args) {
String cash = "R$1,000.75"; //The loop below will work for ANY currency as long as it does not start with a digit
boolean continueLoop = true;
char[] cashArray = cash.toCharArray();
int cpt = 0;
while(continueLoop){
try
{
double d = Double.parseDouble(cashArray[cpt]+"");
continueLoop = false;
}catch(NumberFormatException nfe){
cpt += 1;
}
}
System.out.println(cpt);
//From here you can do whatever you want....
String extracted = cash.substring(cpt);
NumberFormat format = NumberFormat.getInstance(Locale.US); //YOUR REQUIREMENTS !!!! lol
try {
Number youValue = format.parse(extracted);
System.out.println(youValue.doubleValue());
} catch (ParseException ex) {
//handle your parse error here
}
}
You should get as result here in the output:
2
1000.75

Related

Creating a Search Button (Double cannot converted to String)

private void searchProduct()
{
try {
Product p = new Product();
//Read data
p.setId(Double.parseDouble(textID.getText()));
//Display data
textDescription.setText(String.valueOf(p.getDescription()));
textPrice.setText(String.valueOf(p.getUnitPrice()));
textUOM.setText(String.valueOf(p.getUnitOfMeasurement()));
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(this.frame, "ID must be number", "Error",JOptionPane.ERROR_MESSAGE);
}
}
Hello recently I tried to put a button "Search" to find a product than equals to ID, but I don't know how to parse the ID than comes from the product class, I have a error.
Does the textID.getText() actually is a parseable double string? For instance "10.1" do but "10.1 " no.
Always I did this kind of conversion I use trim() to remove this extra white spaces as follow:
String stringValue = textID.getText();
if(stringValue != null) {
stringValue = stringValue.trim();
}
double doubleValue = Double.parseDouble(stringValue);
Se here http://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#valueOf-java.lang.String- how to avoid NumberFormatException using a regular expression to text you string before try to convert it to double.

NumberFormat : setMaximumFractionDigits - not giving expected results

Trying to figure out why the following code is not outputting expecting results. Please advise. Thank you.
import java.text.*;
public class Test {
public static void main(String[] args) {
String s = "987.123456";
double d = 987.123456d;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(5);
System.out.println(nf.format(d) + " ");
try {
System.out.println(nf.parse(s));
} catch (Exception e) {
System.out.println("got exc");
}
}
}
Output:
987.12346 // Expected 987.12345 not 987.12346
987.123456
Your second print doesn't format the double you've parsed.
// System.out.println(nf.parse(s));
System.out.println(nf.format(nf.parse(s))); // <-- 987.12346
To get the output you asked for, you can add a call to NumberFormat#setRoundingMode(RoundingMode) - something like
nf.setMaximumFractionDigits(5);
nf.setRoundingMode(RoundingMode.DOWN);

How to convert %02d:%02d:%02d in to double?

I am setting time on a TextView using
Min_txtvw.setText(String.format(mTimeFormat, hour, min, sec));
Now
average=distance*60*60/seconds // my function for finding average
for seconds i have to get time from Min_txtvw
I done it like below but it gives NumberformatException,
try {
String s = Min_txtvw.getText().toString();
double d = Double.valueOf(s.trim()).doubleValue();
System.out.println("average distance is"+d);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
How i convert that TextView value and convert it in double ?
You are getting NumberformatException because your variable S contains ":" String value, you need to replace those values by using replaceAll() method.
Try following way,
try {
String s = Min_txtvw.getText().toString();
s.replaceAll ( ":","" );
double d = Double.valueOf(s.trim()).doubleValue();
System.out.println("average distance is"+d);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

Doubles, commas and dots

I'm making an Android Java program which is taking double values from the user. If I run the program on the computer, it works great because of the locale of my computer, EN_UK. But when I run it on my mobile phone with FI_FI locale, it won't work. I know the reason: In UK, people use dot as decimal separator but here in Finland, the decimal separator is comma.
DecimalFormat df = new DecimalFormat("#.#");
Double returnValue = Double.valueOf(df.format(doubleNumber));
When I'm using comma, it says java.lang.NumberFormatException: Invalid double: "1234,5".
How can I make it work with them both, comma and dot?
Use one of the other constructors of DecimalFormat:
new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.US))
And then try and parse it using both separators.
using DecimalFormatSymbols.getInstance() will produce the default locale's correct symbols, so you will get it right for any platform you run on.
DecimalFormat df = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance());
This should work for both Java(Tested) as well as android :)
Class Name: In18Helper.java
package com.akmeher.app.utils;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class In18Helper {
private final static In18Helper mHelper = new In18Helper();
public static final In18Helper getInstance() {
return mHelper;
}
public double getDouble(String sValue, Locale locale) {
NumberFormat numberFormat = NumberFormat.getInstance(locale);
Number parse = null;
try {
parse = numberFormat.parse(sValue);
} catch (ParseException e) {
e.printStackTrace();
}
return parse == null ? 0 : parse.doubleValue();
}
}
Class Name: Application.java
package com.akmeher.app;
import java.util.Locale;
import com.akmeher.app.utils.In18Helper;
public class Application {
static DataModel[] testData = new DataModel[] {
new DataModel("1.034567", Locale.ENGLISH),
new DataModel("1,0345.67", Locale.ENGLISH),
new DataModel("1.0345,67", Locale.GERMANY),
new DataModel("1,034,567", Locale.CANADA),
new DataModel("1.034567", Locale.KOREA),
new DataModel("1,03.4567", Locale.ITALY) };
/**
* #param args
*/
public static void main(String[] args) {
for (int i = 0; i < testData.length; i++) {
double d = In18Helper.getInstance().getDouble(testData[i].mValue,
testData[i].mLocale);
System.out.println("Trial Value: "+testData[i].mValue+" for Locale: "+testData[i].mLocale+" converted to: "+d);
}
}
private static class DataModel {
String mValue;
Locale mLocale;
public DataModel(String value, Locale locale) {
this.mLocale = locale;
this.mValue = value;
}
}
}
Output:
Trial Value: 1.034567 for Locale: en converted to: 1.034567
Trial Value: 1,0345.67 for Locale: en converted to: 10345.67
Trial Value: 1.0345,67 for Locale: de_DE converted to: 10345.67
Trial Value: 1,034,567 for Locale: en_CA converted to: 1034567.0
Trial Value: 1.034567 for Locale: ko_KR converted to: 1.034567
Trial Value: 1,03.4567 for Locale: it_IT converted to: 1.03
Hope this will help somebody to make use of.
public static Double parseDoubleTL(String value){
DecimalFormat df = new DecimalFormat("#.#", new DecimalFormatSymbols(new Locale("tr_TR")));
Double doublePrice = 0.0;
try {
doublePrice = df.parse(value).doubleValue();
} catch (ParseException e) {
Log.w(MainActivity.TAG,"Couldnt parse TL. Error is "+e.toString());
}
return doublePrice;
}
Not a best way but worked for me;
Double val=null;
try{
val=Double.valueOf(value);
}catch(Exception e){
val=Double.valueOf(value.replace(',','.'));
}
Double val=null;
try{
val=Double.valueOf(value);
}catch(Exception e){
val=Double.valueOf(value.replace(',','.'));
}
return val;
Me Error:
java.lang.NumberFormatException: Invalid float: "1,683.88"
... and this work for me
replace(",", "")
DecimanFormat df = new DecimalFormat("#.#");

How to validate Hour and Minutes that came from a Swing textBox?

I have a window that contains a HH:mm time TextField in it, in 24 hours format
I need to validate if the user entered any non valid hour, like 28:00, 99:00, 24:01.
What's the best and simpler way to do that ?
some code below of what is currently doing that job wrong and giving errors in date parsed.
Today I get an random hour and an user hit 99:99 in that text field.
This code is not mine, but I gotta fix it.
I am stuck with it, tried to validate as a String is useless, and I cannot find a nice way to make it a Date without having to put year, month, etc... too.
Please forget about the return -1 instead of throwing an exception this is old code and this cannot be changed.
to help understand :
Statics.hF2 = SimpleDateFormat (HH:mm)
this.cmpHora.getText() = Is the field with the value
Statics.df_ddmmyy = Another date format
Statics.m2ms = converts minutes to milliseconds
//CODE
public long getDataEmLong ()
{
try
{
Calendar hour= Calendar.getInstance();
new GregorianCalendar().
hour.setTime( Statics.hF2.parse( this.cmpHora.getText() ) );
return Statics.df_ddmmyy.parse( this.cmpData.getText() ).getTime() + Statics.m2ms( hour.get( Calendar.HOUR_OF_DAY ) * 60 ) + Statics.m2ms( hour.get( Calendar.MINUTE ) );
} catch ( Exception e )
{
e.printStackTrace();
return -1;
}
}
Cheers !
Regular expressions to the rescue:
public boolean validTime24(String time) {
return time.matches("^([01]\d|2[0-3]):[0-5]\d$")
}
This will validate the format of the string. Then you can parse out the time from there.
Insert this in your class, and perform the validateTime method from inside your junk code.
public boolean validateTime(String timeString) {
if (timeString.length() != 5) return false;
if (!timeString.substring(2, 3).equals(":")) return false;
int hour = validateNumber(timeString.substring(0, 2));
int minute = validateNumber(timeString.substring(3));
if (hour < 0 || hour >= 24) return false;
if (minute < 0 || minute >= 60) return false;
return true;
}
public int validateNumber(String numberString) {
try {
int number = Integer.valueOf(numberString);
return number;
} catch (NumberFormatException e) {
return -1;
}
}
You can use JFormattedTextField with proper Date or Time Format set. The field will return you proper values.
Since Java 8 you can use DateTimeFormatter:
public boolean validate(String time) {
try {
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
timeFormatter.parse(time);
return true;
} catch (DateTimeParseException e) {
return false;
}
}

Categories

Resources