-1

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

Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92
  • 1
    You could probably have found the answer to this online or by yourself, so in the future try to include what you've tried and where you've looked :) – dwb Apr 21 '21 at 09:55
  • `double value = Double.parseDouble(Printprice.replaceAll("\\p{Sc}",""));`. Use proper naming for your variables and use the proper parser for your data type. The replaceAll() removes all currency symbols like $ Dollar, € Euro, ¥ Yen". – DevilsHnd - 退職した Apr 21 '21 at 09:59

3 Answers3

2

First problem

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):

Second problem

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

Other approach

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));

Things woth noting

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.

dan1st
  • 12,568
  • 8
  • 34
  • 67
0

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());
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
0
String price ="$157.30";
float value = Float.parseFloat(price.replace("$",""));
System.out.println(value);
Anmol Parida
  • 672
  • 5
  • 16
  • 4
    Code only answer are not the best way to help someone who is having a problem. Try to articulate your train of thoughts, explain what are you doing, put yourself in the shoes of the asker. – Ema.jar Apr 21 '21 at 15:43