Home > Software design >  flutter problem : How to convert this type of double from string?
flutter problem : How to convert this type of double from string?

Time:05-04

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

CodePudding user response:

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

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

CodePudding user response:

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);
}

CodePudding user response:

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
}
  • Related