I want to print 157.30 but print 15730
The code is
String Printprice="$157.30";
double value = Integer.parseInt(Printprice.replaceAll("[^0-9]",""));
Output: 15730
I want to print 157.30 but print 15730
The code is
String Printprice="$157.30";
double value = Integer.parseInt(Printprice.replaceAll("[^0-9]",""));
Output: 15730
Printprice.replaceAll("[^0-9]","")
removes everything that is not a digit, also the decimal point.
If you want to keep the decimal point, you need to change the regex to [^0-9.]
(note the .
after the 0-9
):
Furthermore, Integer.parseInt
parses an int, not a double. If you want a double
, you should use Double.parseDouble
instead:
double value = Double.parseDouble(Printprice.replaceAll("[^0-9.]",""));
If you just want everything after the first character, you can use String#substring
in order to remove the first character:
double value = Double.parseDouble(Printprice.substring(1));
It shoud also be noted that variables should be camelCase by convention. Instead of Printprice
, you should use printPrice
:
String printPrice="$157.30";
double value = Double.parseDouble(printPrice.substring(1));
Yet another thing worth noting is that you shouldn't use IEEE floating point numbers for currency calculations as those are a bit weird. Instead, you may want to save the price in cents (as a long
value) or use NumberFormat
/Currency
as suggested by Achintya Jha.
Try using NumberFormat class https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html
NumberFormat numberformat = NumberFormat.getCurrencyInstance();
Number number = null;
try {
number = numberformat.parse("$157.30");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(number.toString());
String price ="$157.30";
float value = Float.parseFloat(price.replace("$",""));
System.out.println(value);