Commas causing issue in $ value String to Float conversion - java

I'm trying to convert dollar amounts from a text file to a stored numeric type (therefore 'String' to float,BigDecimal,etc)
Problem is that some of the strings include commas: 1,270.00, 22,835.22, etc and return a "java.lang.NumberFormatException:" when trying to be converted.
String GrossEarnings = null;
GrossEarnings = br.readLine();
float GE = Float.parseFloat(GrossEarnings);
String GrossEarnings = null;
GrossEarnings = br.readLine();
BigDecimal GE = new BigDecimal(GrossEarnings);
Is there a way to convert a String of numbers with commas to a numeric type? Or do the commas have to be removed?

Related

How to convert string with $ sing in it to int

I have a string "$1,076.00" and I want to convert them in to int,
I capture some value $1,076.00 and saved in string called originalAmount,
and tried int edited = Integer.parseInt(originalAmount); and it gave me error java.lang.NumberFormatException: For input string: "$1,076.00"
can anyone help?
You need to remove the undesired part ($ sign) and then parse the string to double carefully since the decimal part is a locale dependent
String pay = "$1,076.00";
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse(pay.replace("$", ""));
double result = number.doubleValue();
System.out.println(result);
string sourceString = "$1,076.00";
sourceString.substring(1, sourceString.length() - 1)
int foo = Integer.parseInt(sourceString);
Try this:
String amount = "$1,076,.00";
String formatted = amount.replace("$", ""); // remove "$" sign
formatted = formatted.replace(",", ""); // remove "," signs from number
double amountDouble = Double.parseDouble(formatted); // convert to double
int amountInt = (int)amountDouble; // convert double value to int
System.out.println(amountInt); // prints out 1076
String originalAmount="$1076.00";
String amount = originalAmount.replace($,"");
int edited = Integer.parseInt(amount);
Thanks everyone yr answers help me a lot
I have come up with
originalAmount = originalAmount.substring(1);
if (originalAmount.contains("$")) {
originalAmount = originalAmount.replace("$", "");
}
newOriginalAmt = Double.parseDouble(originalAmount);
System.out.println(newOriginalAmt);
pls let me know yr thoughts

Convert $16500.00 String to 16500 Integer

Im having an issue trying to convert $16500.00 String to 16500 Integer.
This is what i have at the moment but its failing with:
FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid int: "[]"
The code i have is:
String depTest = mDepositAmount.getText().toString();
String deptest2 = Arrays.toString(depTest.replace("R", "").replace(",", "").split("."));
int dep = Integer.parseInt(deptest2);
Please could you help me with getting the end result to 16500. I know how to convert it to int by using Integer.parseInt its just im struggling to get the end result to be 16500 in String
Does your original string always starts with character '$' and followed by number format?
If so try this one:
String org = "$16500.00";
String numbersOnly = org.substring(1); // "16500.00"
int yourInteger = (int)(Float.parseFloat(numbersOnly));
// if you need String, convert it to String again
String integerString = Integer.toString(yourInteger);
You could use a DecimalFormat
import java.text.*;
NumberFormat nf = new DecimalFormat("$0.00");
int value = (int) nf.parse("$16500.00");
You can try with this
String getValue = "$16500.00";
String removeFirstCharecter = getValue.substring(1); // "16500.00"
String [] getString = removeFirstCharecter.split("\\.");
String firstIntValue = (getString[0]); //16500
String sirstIntValue = (getString[1]); //00
Now you can convert firstIntValue String to Integer .
String getRequiredValue = Integer.toString(firstIntValue); //16500
It may be happen because of $ sign so, Just take one another Text view only for Price 16500 and other for $ sign. then convert the Integer.parseInt(textview.getText().toString);

Java, Format String with indexed whitespace

I have my String, "08000001066". This String, which is a telephone number should be displayed with correct format as, "0800 000 1066".
One person suggested i should use this code block,
DecimalFormatSymbols phoneNumberSymbols = new DecimalFormatSymbols();
phoneNumberSymbols.setGroupingSeparator(' ');
DecimalFormat phoneNumberFormat = new DecimalFormat("####,###,###", phoneNumberSymbols);
This results in something close to what i want, but not exact as the DecimalFormat required a number (double, or float - of which a zero leading string cannot be parsed).
How would i format a String by method of something like Decimal Format's ####,###,###?
String phoneNumber = "08000001066";
StringBuilder sb = new StringBuilder(phoneNumber)
.insert(4," ")
.insert(8," ");
String output = sb.toString();
Try this out, it relies on your input being the correct number of digits but works with leading zeroes.
String inputString = "08000001066";
java.text.MessageFormat phoneFormat = new java.text.MessageFormat("{0} {1} {2}");
String[] phoneNumberArray = {inputString.substring(0,4), inputString.substring(4,7), inputString.substring(7)};
System.out.println(phoneFormat.format(phoneNumberArray));
Pattern p = Pattern.compile("(\\d{4})(\\d{3})(\\d{4})");
String s = "08000001066";
Matcher m = p.matcher(s);
if(m.matches()) {
return String.format("%s %s %s", m.group(1), m.group(2), m.group(3)));
}

Decimal Format, says it needs to be a string?

I'm getting the error "cannot convert from String to Double" when I run this code, any ideas?
DecimalFormat df = new DecimalFormat("##.###");
String [] data = null;
data = str.split(" ");
Double bat_avg = Double.parseDouble(data[4])/Double.parseDouble(data[2]);
bat_avg = df.format(bat_avg);
System.out.println(bat_avg);
DecimalFormat#format(double) returns a String so the output needs to be this type rather than a Double:
String output = df.format(bat_avg);

Is it possible to ignore Float :: = HexFloat and only see numeric characters?

I'm trying to parse the string value "87306E107" using hasNextDouble. This value is a string and should return false when using hasNextDouble but it returns true. I want know if it's possible to have this method return false? The reason I want to treat this value as a string is because I have to wrap it in single quotes for building a dynamic database insert statement. Here is my code below:
String data = "87306E107,27.1,xyz,123,01449J204";
Scanner scanner = new Scanner(data);
scanner.useDelimiter(",");
if (!scanner.hasNextInt() && !scanner.hasNextDouble()){
if (DateUtils.isDate(data)){
//Format date to correct layout
data = DateUtils.parseStringDate(data, "yyyy-MM-dd", 0);
}
//Escape any single quotes
data = data.replaceAll("'", "''");
//Wrap in single quotes
data = "'" + data + "'";
}
You can try a string matcher instead of hasNextDouble():
scanner.hasNext("\\d+(\\.\\d+)?")

Categories

Resources