Himanshu Thakur
Himanshu Thakur

Reputation: 61

how to get a double value out of a string in dart?

I have a list of strings to be shown in a dropdown.i.e.

String selectedLeverage = '1 : 100';
final leverageSelected = TextEditingController();
List<String> leverage = [
     "1 : 1",
     "1 : 2",
     "1 : 5",
     "1 : 10",
     "1 : 50",
     "1 : 100",
     "1 : 200",
     "1 : 500",
     "1 : 800",
     "1 : 1000",
     "1 : 2000",
     "1 : 3000",
     ];

What I want: I want to extract the last element of the string as a double value when any particular value is selected from the dropdown to do calculations in the future. (e.g. In case, the user chose 1:100 from the dropdown, I want to have 100 as a double out of the string "1:100" which I am getting from the list leverage )

What I am doing:

  double leverage = double.parse('$selectedLeverage.split(" ")[2]');
  print(leverage); // i am expecting to get a doble value here =100.0 but this is giving me 1.0 

Here

   selectedLeverage.split(" ")

is converting the the string "1:100" in to a list ["1",":","100"] and I am trying to convert "100" to double 100.0 by using

   double.parse('$selectedLeverage.split(" ")[2]')

I don't know where I am doing wrong.

Upvotes: 0

Views: 1055

Answers (2)

Himanshu Thakur
Himanshu Thakur

Reputation: 61

I eventually figured out the mistake myself everything was right but the problem was in the dropdown. The value of selected leverage wasn't changing on selecting different leverage value

Upvotes: 0

TSR
TSR

Reputation: 20647

Add the curly brackets

double.parse('${selectedLeverage.split(" ")[2]}')

Or just remove quotes

double.parse(selectedLeverage.split(" ")[2])

Upvotes: 1

Related Questions