perl - 如何将 4.44445 舍入到 4.45?
问题描述
有谁知道这个模块不是二进制的,而是下一个:
4.444435 -> 4.44
4.444445 -> 4.45
4.445444 -> 4.45
4.443000 -> 4.44
, sprintf
,不能那样做 = Math::BigFloat
(Math::BigRat
解决方案
我仍然不明白规则是如何工作的,但是使用bfround
Math ::BigFloat可能会返回你想要的。
#!/usr/bin/perl
use warnings;
use feature qw{ say };
use Math::BigFloat;
sub myround {
my $bi = 'Math::BigFloat'->new("$_[0]");
for (my $l = length $bi; $l > 1; --$l) {
$bi->bfround(-$l, '+inf');
}
$bi
}
use Test::More tests => 8;
is myround(4.444435), 4.44;
is myround(4.444445), 4.45;
is myround(4.445444), 4.45;
is myround(4.443000), 4.44;
is myround(3.554444), 3.55;
is myround(3.554445), 3.56;
is myround(3.544445), 3.55;
is myround(3.555550), 3.56;
推荐阅读
- python - 为什么我在 CBC 中使用 AES 256 的代码即使没有填充也能工作?
- regex - 如何使用正则表达式屏蔽除最后四位数字外的信用卡号码
- c++ - 如何分析在 Windows 上运行的 C++ 代码?
- android - 在没有 IDE 的移动设备上构建 android 应用程序
- typo3-9.x - Typo3:Powermail 扩展 Ajax 提交
- aws-lambda - SAM 使用环境变量在容器中构建
- angular - 如何从 HTML 模板传递 Ng 组件的通用类型
- mysql - 使用 HDP mariadb 服务器部署 HDF
- rx-java - 何时在 RxJava 中使用阻塞订阅
- javascript - 添加行的多个插入