在Perl中处理美元计算的最佳技术是什么? [英] What's the best technique for handling US Dollar calculations in Perl?
本文介绍了在Perl中处理美元计算的最佳技术是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Perl中处理美元计算的最佳技术是什么?
What's the best technique for handling US Dollar calculations in Perl?
尤其是:需要满足以下要求:
Especially: the following needs to work:
$balance = 10;
$payment = $balance / 3; # Each payment should be 3.33. How best to round amount?
$balance -= $payment * 3;
# assert: $balance == .01
推荐答案
请参见 Math :: Currency 。
已更新:
假设所有付款加起来为余额,我想出了以下脚本 Greg Hewgill提出的观点:
Assuming all payments adding up to the balance is desirable, I came up with the following script based on the points made by Greg Hewgill:
#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw( sum );
my @balances = (10, 1, .50, 5, 7, 12, 3, 2, 8, 1012);
for my $balance (@balances) {
my @stream = get_payment_stream($balance, 3);
my $sum = sum @stream;
print "$balance : @stream : $sum\n";
}
sub get_payment_stream {
my ($balance, $installments) = @_;
$balance *= 100;
my $payment = int($balance / $installments);
$installments -= 1;
my $residual = $balance - int($payment * $installments);
my @stream = (($payment) x $installments, $residual);
return map { sprintf '%.2f', $_ / 100} @stream;
}
输出:
C:\Temp> p
10 : 3.33 3.33 3.34 : 10
1 : 0.33 0.33 0.34 : 1
0.5 : 0.16 0.16 0.18 : 0.5
5 : 1.66 1.66 1.68 : 5
7 : 2.33 2.33 2.34 : 7
12 : 4.00 4.00 4.00 : 12
3 : 1.00 1.00 1.00 : 3
2 : 0.66 0.66 0.68 : 2
8 : 2.66 2.66 2.68 : 8
1012 : 337.33 337.33 337.34 : 1012
这篇关于在Perl中处理美元计算的最佳技术是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文