What is the best method of processing settlements in US dollars in Perl?

What is the best technique for handling US dollar calculations in Perl?

In particular: you must perform the following steps:

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

See Math :: Currency .

Updated:

Assuming that all payments adding balance are desirable, I came up with the following point- based script made by Greg Hugill :

#!/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;
}

Output:

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
+7

- , . , 10 1000 (), 333 3,33 .

, 10 , - 3,33, 3,33 $3,34. , -, .

+10

Math:: Currency;

- :)

0

Source: https://habr.com/ru/post/1715028/


All Articles