Reputation: 1528
I have a huge rational number, which I need to convert to a decimal number. How can I do this?
The rational was created like this:
my $t;
{
use bigrat;
$t = (3 ** 1000) / (2 ** 1000);
}
I need to get the result $t in decimal form (integer part -dot- a few decimal digits)
How can I do that conversion?
Upvotes: 1
Views: 108
Reputation: 126742
bigrat
tries to do everything transparently by overloading operators so that you can work without being aware of the underlying objects being used. But it can't always get everything right, and you need to use Math::BigRat
directly to get the necessary control over the format of the intermediate numbers.
This code does what you ask. The parameter to as_float
says how many digits you want in the output. Since 31000 ÷ 21000 is greater than 1e176 you need something more than 176 to show the decimal point at all. A value of 200 shows the first 23 decimal places.
use strict;
use warnings;
use 5.010;
use Math::BigRat;
my $t = do {
my $num = Math::BigRat->new(3) ** 1000;
my $den = Math::BigRat->new(2) ** 1000;
$num / $den;
};
say $t->as_float(200);
output
123384059690617347922743909948678005742186900514842808542522975184329422623652841193932245134021231941529455308114511924428000273557831297406949841351167568024301164105271903064.98735542425778400198655
Upvotes: 3
Reputation: 386331
That's the same as
use Math::BigRat qw( );
my $t = (Math::BigRat->new(3) ** Math::BigRat->new(1000))
/ (Math::BigRat->new(2) ** Math::BigRat->new(1000));
Math::BigRat provides
->as_float()
to get a Math::BigFloat
->numify()
to get a regular floating point number scalar.
Upvotes: 2