Net Nanny
Net Nanny

Reputation: 53

How to Convert String to Double in Java

I want to convert a string (for example $4.50) to a double. I understand I can use Double.parseDouble() but I assume this works only if the string does not contain any other chars (such as the dollar sign). The purpose is to compare two Strings (which contain dollar values plus a dollar sign) and determine which one is greater and which one is smaller

How can I convert such a string to a double?

Upvotes: 2

Views: 2412

Answers (4)

Santosh Kusanale
Santosh Kusanale

Reputation: 66

Try this Double.parseDouble(yourString.substring(1))

Upvotes: 1

Vignesh Shiv
Vignesh Shiv

Reputation: 1157

Hope this would help,

Double.parseDouble(string.replaceAll("[^\\d.]", "")); 

Upvotes: 0

karthik manchala
karthik manchala

Reputation: 13650

You can do the following:

Double.parseDouble(string.replaceAll("[$]", "")); 

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174874

Use Double.parseDouble after removing the unwanted characters like currency symbols.

Double.parseDouble(string.replaceAll("[^\\d.]", "")); 

This would removed any character but not of a dot or a digit.

Upvotes: 2

Related Questions