一、Flutter 中的數字處理
在 Flutter 中,數字通常用於計算和統計的目的。在處理數字的過程中,我們可能需要保留一定的小數位數以避免精度損失。Flutter 提供了許多方法來處理數字,並且支持各種數據類型,例如 int、double 等。
在 Flutter 中,有兩種基本的數據類型用於表示數字:
int numValue = 100;
double doubleValue = 100.00;
其中,int 類型只能表示整數,而 double 類型可以表示浮點數。
在處理數字時,我們可以使用以下方法:
1. toFixed()
toFixed() 方法可以使用指定位數(例如 2)來格式化數字。例如:
double numValue = 123.456789;
String formattedNum = numValue.toStringAsFixed(2); // 小數點後面保留 2 位
print(formattedNum); // 輸出 123.46
該方法會將數字四捨五入到指定的小數位數。
2. truncateToDouble()
truncateToDouble() 方法可以使用指定的小數位數(例如 2)截取數字的小數部分。例如:
double numValue = 123.456789;
double truncatedValue = numValue.truncateToDouble();
String formattedNum = truncatedValue.toStringAsFixed(2); // 小數點後面保留 2 位
print(formattedNum); // 輸出 123.45
這個方法不會改變原始的數字,而只是返回一個新的數字。
二、Flutter 中的小數處理
在 Flutter 中,如果需要對小數進行取整或格式化,可以使用以下方法:
1. round()
round() 方法可以四捨五入到最接近的整數。例如:
double numValue = 123.5678;
int roundedValue = numValue.round();
print(roundedValue); // 輸出 124
該方法會將數字四捨五入到最接近的整數。
2. ceil()
ceil() 方法向上取整,例如:
double numValue = 123.5678;
int ceilValue = numValue.ceil();
print(ceilValue); // 輸出 124
該方法始終返回最接近數字的上限。
3. floor()
floor() 方法向下取整,例如:
double numValue = 123.5678;
int floorValue = numValue.floor();
print(floorValue); // 輸出 123
該方法返回最接近數字的下限。
三、完整示例代碼
double numValue = 123.456789;
String formattedNum = numValue.toStringAsFixed(2);
print(formattedNum); // 輸出 123.46
double truncatedValue = numValue.truncateToDouble();
String formattedTruncatedValue = truncatedValue.toStringAsFixed(2);
print(formattedTruncatedValue); // 輸出 123.45
double roundValue = 123.5678;
int roundedValue = roundValue.round();
print(roundedValue); // 輸出 124
double ceilValue = 123.5678;
int ceilNum = ceilValue.ceil();
print(ceilNum); // 輸出 124
double floorValue = 123.5678;
int floorNum = floorValue.floor();
print(floorNum); // 輸出 123
原創文章,作者:BYZOY,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/362071.html