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
3
Answers
You can call
.split
method on Strings to split them by a specific character. For example we have a String likeString unusualNumber = "Number=22"
, we can callunusualNumber.split['='].last
to extract the number which in our case is22
from it.Solution for your code:
actualRatio
will be 16 / 9 as a double.Read more about
split
method:https://api.flutter.dev/flutter/dart-core/String/split.html
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:It is better to store these in the form of two separate variables i.e.,
height
andwidth
.That gives you the flexibility to combine these as a
String
like "16/9" or "16:9" or represent as adouble
like "1.77".