How can I format a number as currency in Perl? - perl

How I can format this for example:
100000 as 1000.00
and
90 as 0.90
using Perl?
I found and try with some modules like Locale::Currency::Format and Number::Format, but nothing work :/
With Locale::Currency::Format I try:
use Locale::Currency::Format;
my $total = 19750;
my $convert = currency_format('USD',$total,'FMT_COMMON');
print $convert;
I've expect 197.50 but the print are "19,750.00 USD".

my $formatted = sprintf '%.2f', $number/100.0;
In US currency we count dollars, not cents. If you want to use integers representing pennies to avoid rounding errors, that's great; good practice. But it's up to you to divide by 100 to get human-legible output in the standard format.
The sprintf function (string print formatted, originally from the C standard library and now found in many programming languages) will format numbers in a variety of ways. In this case, the format string %.2f requests output of a floating-point (i.e. decimal, fractional, real, non-integer) number with 2 digits after the decimal point.

To convert cents into dollars, divide by 100!
sprintf("%.2f", $total/100) # 197.50
or
currency_format('USD', $total/100, 'FMT_COMMON') # 197.50 USD

Update for late 2022:
Using this method:
use Locale::Currency::Format;
...
$dollars = currency_format('USD',1,624.98,FMT_SYMBOL);
Outputs this:
$1.00
I have just run into this issue and had to insert this before the format:
use Locale::Currency::Format;
...
$dollars =~ s/\,//g; #<----------
$dollars = currency_format('USD',$dollars,FMT_SYMBOL);

Related

How do I display a large number in scientific notation?

Using AutoIt, when I multiply 1 by 10^21, I get 1e+021. But in separate steps, such as multiplying 1 by 10^3 seven times, I get the overflow value of 3875820019684212736.
It appears AutoIt cannot handle numbers with more than eighteen digits. Is there a way around this? For example, can I multiply 10,000,000,000,000,000 by 1000 and have the result displayed as 1e+019?
Try this UDF : BigNum UDF
Example :
$X = "9999999999999999999999999999999"
$Y = "9999999999999999999999999999999"
$product = _BigNum_Mul($X, $Y)

Number Formatting from $100000 to $100 000,00

Can someone please help format this number: $100000 to $100 000,00. (in words: Hundred Thousand dollars) or if million it must format $100000 to $1 000 000,00
I only know of the standard .NET decimal.ToString( "N2" ) e.g.
decimal number = 1000000d;
string formatedNumber = number.ToString( "N2" ); // This will give you 1,00,000.00
Is there a standard .NET format I can re-use or will I have to create my own?
decimal number = 1000000;
Console.WriteLine(number.ToString("C"), System.Globalization.CultureInfo.CreateSpecificCulture("en-US")); // 1 000.000,00
'C' stands for currency, so yes, there is a standard format for it.

How do I round up a float whose mantissa is ending in 5?

I want to round up a floating-point number. For example, sprintf '%.4f', 0.12345 returns 0.1235 and sprintf '%.4f', 0.12325 returns 0.1232. For the second example, I want it to print out 0.1233, not 0.1232.
sprintf in Perl is not good enough. Math::BigFloat can do it, but it’s a little over-kill.
Does anyone know if there is other effective way to round up, or whether there is any other module in Perl?
The exact way sprintf will round a number is dependent on how the system libraries round numbers. If you need to control exactly how a number is rounded you will need to use a library that implements your desired rounding explicitly, or write a function to round as desired.
For example to round a positive number to an arbitrary precision, where 5 rounds up this would work.
sub round {
my $numer = shift;
my $precision = shift;
return int($numer * 10 ** $precision + 0.5) * 10 ** -$precision;
}
This however doesn't round correctly for negative numbers, -0.12324 incorrectly rounds to -0.1231. A solution where 5 should round up (that is towards positive infinity) would be to use floor instead of int.
use POSIX qw(floor);
sub round {
my $numer = shift;
my $precision = shift;
return floor($numer * 10 ** $precision + 0.5) * 10 ** -$precision;
}
If instead 5 should round to the largest absolute value (that is round away from 0) then you can add a simple check for negative numbers to round them in the correct direction.
sub round {
my $numer = shift;
my $precision = shift;
my $direction = $numer >= 0 ? 0.5 : -0.5;
return int($numer * 10 ** $precision + $direction) * 10 ** -$precision;
}
There are more complex rules for rounding used in some circumstances where the bias from rounding 5 in one direction for all numbers is unacceptable and any (decimal) rounding of floating point numbers is subject to possible errors due to imprecision in their binary format.
Perl's sprintf can only be as good as the data it's fed.
There is no floating point number equal exact to either 0.12345 or 0.12325:
The floating point number closest to the 0.12345 is exactly 2223877495995551/2**54 ≈ 0.123450000000000004, a value slightly greater than the input.
The floating point number closest to the 0.12325 is exactly 4440549232587309/2**55 ≈ 0.123249999999999998, a value slightly less than the input.
Note that the 5th decimal digit of the latter one is 4 not 5.
When rounded to 4 decimal places under the usual rules, they must come out as 0.1235 and 0.1232 respectively.
You say that using Math::BigFloat is a little overkill, but it seems that what you really want is decimal arithmetic so the overkill is inescapable.
This did work for me:
print sprintf '%.*f', 4, 0.12325
Your code does work for me too. Did you test that code on its own?
Could you tell us your perl version too (perl -v)?

How to get Exponent of Scientific Notation in Matlab

When the numbers are really small, Matlab automatically shows them formatted in Scientific Notation.
Example:
A = rand(3) / 10000000000000000;
A =
1.0e-016 *
0.6340 0.1077 0.6477
0.3012 0.7984 0.0551
0.5830 0.8751 0.9386
Is there some in-built function which returns the exponent? Something like: getExponent(A) = -16?
I know this is sort of a stupid question, but I need to check hundreds of matrices and I can't seem to figure it out.
Thank you for your help.
Basic math can tell you that:
floor(log10(N))
The log base 10 of a number tells you approximately how many digits before the decimal are in that number.
For instance, 99987123459823754 is 9.998E+016
log10(99987123459823754) is 16.9999441, the floor of which is 16 - which can basically tell you "the exponent in scientific notation is 16, very close to being 17".
Floor always rounds down, so you don't need to worry about small exponents:
0.000000000003754 = 3.754E-012
log10(0.000000000003754) = -11.425
floor(log10(0.000000000003754)) = -12
You can use log10(A). The exponent used to print out will be the largest magnitude exponent in A. If you only care about small numbers (< 1), you can use
min(floor(log10(A)))
but if it is possible for them to be large too, you'd want something like:
a = log10(A);
[v i] = max(ceil(abs(a)));
exponent = v * sign(a(i));
this finds the maximum absolute exponent, and returns that. So if A = [1e-6 1e20], it will return 20.
I'm actually not sure quite how Matlab decides what exponent to use when printing out. Obviously, if A is close to 1 (e.g. A = [100, 203]) then it won't use an exponent at all but this solution will return 2. You'd have to play around with it a bit to work out exactly what the rules for printing matrices are.

How can I write in scientific notation using Perl formats?

I've always used printf, and I've never used write/format. Is there any way to reproduce printf("%12.5e", $num) using a format? I'm having trouble digesting the perlform documentation, but I don't see a straightforward way of doing this.
EDIT: based on the answers I got, I'm just gonna keep on using printf.
Short answer, don't use formats.
Unresearched answer, sure, just use sprintf:
#!/usr/bin/perl
use strict;
use warnings;
our $num = .005;
write;
format STDOUT =
#>>>>>>>>>>>>>>>>>
sprintf("%12.5e", $num)
.
Seriously, if you need something like Perl 5 formats, take a look at Perl6::Form (note, this is a Perl 5 module, it just implements the proposed Perl 6 version of formats).
I totally agree with Chas. Owens on formats in general. Format was really slick 15 years ago, but format has not kept up with the advancements of the rest of Perl.
Here is a technique for line oriented output that I use time to time. You can use formline which is one of the public internal functions used by format. Format is page oriented. It is very hard to do things like span columns or change the format by line depending on the data. You can format a single line using the same text formatting logic used by format and then output that result yourself.
A (messy) example:
use strict; use warnings;
sub print_line {
my $pic=shift;
my #args=#_;
formline($pic,#args);
print "$^A\n";
$^A='';
}
my ($wlabel, $wlow, $whigh, $wavg)=(0,0,0,0);
my ($plabel,$plow,$phigh, $pavg);
my ($s_low,$s_high,$s_avg)=qw(%.2f %.2e %.2f);
my #results=( ["Label 1", 3.445, 0.00006678, .025],
["Label 2", 12.5555556, 55.112, 1.11],
["Wide Label 3", 1231.11, 1555.0, 66.66] );
foreach (#results) {
my $tmp;
$tmp=length($_->[0]);
$wlabel=$tmp if $tmp>$wlabel;
$tmp=length(sprintf($s_low,$_->[3]));
$wlow=$tmp if $tmp>$wlow;
$tmp=length(sprintf($s_high,$_->[2]));
$whigh=$tmp if $tmp>$whigh;
$tmp=length(sprintf($s_avg,$_->[1]));
$wavg=$tmp if $tmp>$wavg;
}
print "\n\n";
my #a1=("Label", "Rate - Operations / sec");
my #a2=("Text", "Average", "High", "Low");
my #a3=("----------", "-------", "----", "---");
my $l1fmt="#".'|' x $wlabel." #".'|'x($whigh+$wavg+$wlow+6);
my $l2fmt="#".'|' x $wlabel." #".'|' x $wavg." #".'|' x $whigh .
" #".'|' x $wlow;
print_line($l1fmt,#a1);
print_line($l2fmt,#a2);
print_line($l2fmt,#a3);
$plabel="#".'>' x $wlabel;
$phigh="#".'>' x $whigh;
$pavg="#".'>' x $wavg;
$plow="#".'<' x $wlow;
foreach (#results) {
my $pic="$plabel $pavg $phigh $plow";
my $mark=$_->[0];
my $avg=sprintf($s_avg,$_->[1]);
my $high=sprintf($s_high,$_->[2]);
my $low=sprintf($s_low,$_->[3]);
print_line($pic,$mark,$avg,$high,$low);
}
print "\n\n";
Outputs this:
Label Rate - Operations / sec
Text Average High Low
---------- ------- ---- ---
Label 1 3.44 6.68e-05 0.03
Label 2 12.56 5.51e+01 1.11
Wide Label 3 1231.11 1.56e+03 66.66
Notice that the width of the columns is set based on the width of the data as formatted by the sprintf format string. You can then left, center, right justify that result. The "Low" data column is left justified, the rest of the data are right justified. You can change this by the symbol used in the scalar $plow and it is the same as format syntax. The labels at the top are centered and the "Rate - Operations / sec" label spans 3 columns.
This is obviously not "production ready" code, but you get the drift I think. You would need to further check the total width of the columns against desired width, etc. You have to manually do some of the work that format does for you, but you have far more flexibility with this approach. It is very easy to use this method for several sections of a line with sprintf for example.
Cheers.