Flutter 變數型別轉換 Int Double String 及 運算結果處理
以下紀錄運算常用到的幾種變數型別互相轉換
文章目錄
Double to Int
無條件捨去小數點
double x = 3.94;
var y = x.toInt();
print(y); // 3
print(y.runtimeType); // int
四捨五入
double a = 9.6;
var b = a.round();
print(b); // 10
print(b.runtimeType); //int
無條件進位
double c = 5.1;
var d = c.ceil();
print(d); //6
print(d.runtimeType); //int
Int to Double
int a = 5;
var b = a.toDouble();
print(b); //5.0
print(b.runtimeType); //double
Double運算產生小數點後多位數
Dart浮點數運算上跟JS一樣會出現精度問題
var a = 1.0;
var b = 1;
var c = 1.1;
a - b = 1.00
c - b = 0.10000000000000000009
0.2 + 0.1 = 0.30000000000000004
有兩個解決方案
不靠套件的方式是把數字放大再取需要的地方
int aInt = (a*100).floor();
int bInt = (b*100).floor();
int cInt = (c*100).floor();
(aInt - bInt)/100 = 1
(cInt - bInt)/100 = 0.1
使用套件的話可用decimal
小數點後去除尾數0
String num = a.toString().replaceAll(RegExp(r"([.]*0*$)"), "");
double a = 12.500; //num = 12.5
double b = 12.0; //num = 12
double c = 1000; //num = 1000
正規表達式收集
doblue = “^(-?)(0|([1-9][0-9]*))(\.[0-9]+)?$"