Deepak
Deepak

Reputation: 2298

flutter problem : How to convert this type of double from string?

I want to convert sting to double , here my double is saperated by comma, So how to do it?

void main() {
  var myInt = int.parse('12345');
  assert(myInt is int);
  print(myInt); // 12345
  print(myInt.runtimeType);  // int
  
  
    var myDouble = double.parse('1,230.45');
  assert(myInt is double);
  print(myDouble); 
  print(myDouble.runtimeType); // double
}

enter image description here

Upvotes: 3

Views: 1722

Answers (3)

jamesdlin
jamesdlin

Reputation: 90184

package:intl's NumberFormat also can parse numbers with commas as grouping separators:

import 'package:intl/intl.dart';

void main() {
  var numberFormat = NumberFormat('#,###.##');
  var myDouble = numberFormat.parse('1,230.45');
  print(myDouble); // Prints: 1230.45
  print(numberFormat.format(myDouble)); // Prints: 1,230.45
}

Upvotes: 0

nitishk72
nitishk72

Reputation: 1746

You need to remove the comma before parsing it. to remove comma you can use replaceAll on Stirng like this

void main() {
  var k1 = '1,230.45';
  var k2 = k1.replaceAll(',','');
  var myDouble = double.parse(k2);
  print(myDouble); 
  print(myDouble.runtimeType);
}

Upvotes: 0

Siddharth Mehra
Siddharth Mehra

Reputation: 1909

You need to remove , first to parse it as double:

var myDouble = double.parse('1,230.45'.replaceAll(',', ''));

Upvotes: 3

Related Questions