Home > Back-end >  Dart/Flutter convert a fraction string to a double
Dart/Flutter convert a fraction string to a double

Time:12-15

If I have a fraction double stored as a string i.e., "16/9", "16 / 9", "9/16", "9 / 16", etc., how can I convert it to a double? Or should I store those differently in order to convert them to doubles to be used as aspectRatio settings? Code example:

String aspectRatio = "16/9";
OR String aspectRatio = "16 / 9";
  
final aspectRatioDouble = double.parse(aspectRatio);
print(aspectRatioDouble); 
/// Throws "Uncaught Error: FormatException: Invalid double 16/9"

final aspectRatioDoubleTry = double.tryParse(aspectRatio);
print(aspectRatioDoubleTry); 
/// Prints null

CodePudding user response:

The function_tree is a useful package for parsing mathematical expressions like yours which are presented as String directly, sample of what it can do:

'16 / 9'.interpret(); // 1.77

CodePudding user response:

You can call .split method on Strings to split them by a specific character. For example we have a String like String unusualNumber = "Number=22", we can call unusualNumber.split['='].last to extract the number which in our case is 22 from it.

Solution for your code:

String aspectRatio = "16/9";
OR String aspectRatio = "16 / 9";

final List<String> split = aspectRatio.split("/");
final double actualRatio = double.parse(aspectRatio.first) / double.parse(aspectRatio.last);

actualRatio will be 16 / 9 as a double. Read more about split method: https://api.flutter.dev/flutter/dart-core/String/split.html

CodePudding user response:

It is better to store these in the form of two separate variables i.e., height and width. That gives you the flexibility to combine these as a String like "16/9" or "16:9" or represent as a double like "1.77".

  • Related