如何在flutter中自定義四舍五入當小數為0.1時它會自動四舍五入但是當小數低于0.1時它會自動向下舍入
例如:
double roundUp = 0.1;
double roundedUp = roundUp.round() // it will become roundedUp = 1
double roundUp = 0.09;
double roundedDown = roundDown.round() // it will become roundedDown = 0
uj5u.com熱心網友回復:
您在問題中提供的資訊不正確。根據檔案:
int round ()
Returns the integer closest to this.
Rounds away from zero when there is no closest integer: (3.5).round() == 4 and (-3.5).round() == -4.
此外,您的代碼片段甚至不會運行。嘗試運行:
void main() {
print(0.1.round()); //prints 0
print(0.09.round()); //prints 0
}
輸出與檔案一致:Returns the integer closest to this.
但是你的問題是不同的,如果你想有一個自定義的輪函式,你可以定義你自己的輪函式或創建一個擴展:
int roundDouble(double x) {
return x.toInt();
}
extension Rounding on double {
int myRound() {
return this.toInt();
}
}
void main() {
print(roundDouble(5.2));
print(5.2.myRound());
}
檢查https://api.dart.dev/stable/2.3.0/dart-core/num/round.html和https://api.dart.dev/stable/2.17.1/dart-core/dart-core -library.html了解更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/483288.html
