Shahbaz
Shahbaz

Reputation: 825

How can I convert String with comma to double in Dart?

I have a text field in which I am taking string as input and converting it to double using double.parse() method.

I am using the number type keyboard for the textfield. But when the user inputs a comma with numbers for example 5,000 my program is giving output of 5.00

How can I get the output of 5000 from 5,000 in dart?

Upvotes: 7

Views: 9867

Answers (4)

Tom Dhanabhon
Tom Dhanabhon

Reputation: 491

Use the NumberFormat() from the intl package.

double price = NumberFormat().parse(_textFieldController.text) as double;

Upvotes: 0

TSoftOne
TSoftOne

Reputation: 301

You need to consider localization. Countries in Europe use comma as decimal separator while the US uses dot.

You need to use NumberFormat from intl package for the complete solution.

String t = '5,000';
double f = NumberFormat().parse(t);
print(f);

NumberFormat() automatically gets initialized with the device's current locale if you don't pass in a locale.

Upvotes: 16

SRR
SRR

Reputation: 1758

For the answer to your final question:

String t = '5,000';
double f = double.parse(t.replaceAll(',',''));
print(f);

Use .replaceAll() to replace all instances of the comma with no character

Upvotes: 15

DEEP SECRETS
DEEP SECRETS

Reputation: 113

you have to remove "," from your input string..

Upvotes: 0

Related Questions