gpt4 book ai didi

dart - 达特银行家的四舍五入

转载 作者:行者123 更新时间:2023-12-03 04:28:08 25 4
gpt4 key购买 nike

任何人都可以在Dart中帮助银行家进行四舍五入吗

所以我绕了3 d.p.到最近的2 d.p.除数字中间的数字时,数字除为最近的偶数

例如

print(1.011.toStringAsFixed(2)); // rounds down to 1.01
print(1.019.toStringAsFixed(2)); // rounds up to 1.02
print(1.015.toStringAsFixed(2)); // rounds down to 1.01 but i want up to 1.02
print(1.025.toStringAsFixed(2)); // rounds down to 1.02

最佳答案

我有相同的要求,所以我建立一个。

banker_rounding.dart

import 'dart:math';

import 'package:decimal/decimal.dart';

Decimal _getDecimalOfNumber(Decimal number, int fractionDigits) => number - (number.floor());

Decimal _pow10(int powNum) => Decimal.parse(pow(10, powNum).toString());

Decimal _carryLatest(Decimal number) {
int decimalLength = number.toString().length - 2;
Decimal offset = _pow10(-decimalLength);
return number + offset;
}

Decimal bankerRound(Decimal value, int fractionDigits) {
// integer of number
Decimal integerOfNumber = value.floor();
// decimal of number
Decimal decimalOfNumber = _getDecimalOfNumber(value, fractionDigits);
// remain flag
int remainFlag = (decimalOfNumber * _pow10(fractionDigits + 1) % Decimal.fromInt(10)).toInt();
Decimal finalMultiple = _pow10(fractionDigits);
Decimal finalDecimalOfNumber = ((decimalOfNumber * finalMultiple).floor() / finalMultiple);
if (remainFlag <= 4) {
// do nothing
} else if (remainFlag >= 6) {
// carry
finalDecimalOfNumber = _carryLatest(finalDecimalOfNumber);
} else {
// check bottom has number
bool hasBottom = _getDecimalOfNumber(decimalOfNumber * _pow10(fractionDigits + 1), fractionDigits) != Decimal.zero;
if (hasBottom) {
// carry
finalDecimalOfNumber = _carryLatest(finalDecimalOfNumber);
} else {
// check pre remain flag
int preLastNumber = (decimalOfNumber * _pow10(fractionDigits) % Decimal.fromInt(10)).toInt();
if (preLastNumber.isOdd) {
// carry
finalDecimalOfNumber = _carryLatest(finalDecimalOfNumber);
} else {
// do nothing
}
}
}
return integerOfNumber + finalDecimalOfNumber;
}

关于dart - 达特银行家的四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57877692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com