在Perl中处理美元计算的最佳技术是什么?

特别是:以下需要工作:

$balance = 10;
$payment = $balance / 3; # Each payment should be 3.33. How best to round amount?
$balance -= $payment * 3;
# assert: $balance == .01

最佳答案

参见Math::Currency

更新:

假设所有付款加起来的余额是可取的,我根据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:\温度> 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

08-28 01:58
查看更多