Acorcdev
Acorcdev

Reputation: 381

How to convert String to Double correctly?

I have read many questions on stackoverflow and didn't get what I want. I have a String with value: "1.000,00" and I want to make it a double and look exactly like this "1000.0" but I can't do it right. Using the code below, I just get "1.0" and this is incorrect. How to do this in the right way? I am using Flutter.

String t = "1.000,00";
double f = NumberFormat().parse(t);

userIncome = f;

Upvotes: 0

Views: 3211

Answers (2)

Midhun MP
Midhun MP

Reputation: 107231

You just need to set the defaultLocale property.

Intl.defaultLocale = 'pt_BR';
String t = "1.000,00";
double f = NumberFormat().parse(t);
print(f); // Prints 1000.0

Upvotes: 3

diogenes_vz
diogenes_vz

Reputation: 87

In your case, is not just a "number", is a currency.

A simple way to deal with it is to convert into a number and parse:

String t = "1.000,00";
// the order of replaces here is important
String formated = t.replace(".", "").replace(",", ".");

userIncome = Double.valueOf(formated);

But, if your application is focus on currency you should take a look in this: https://www.baeldung.com/java-money-and-currency

Upvotes: 1

Related Questions