Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert between scientific and decimal notation in Perl?

I know this is a total newbie question, but the answer may not be obvious to many new programmers. It wasn't initially obvious to me so I scoured the Internet looking for Perl modules to do this simple task.

like image 948
Kurt W. Leucht Avatar asked Mar 19 '10 01:03

Kurt W. Leucht


2 Answers

sprintf does the trick

use strict;
use warnings;

my $decimal_notation = 10 / 3;
my $scientific_notation = sprintf("%e", $decimal_notation);

print "Decimal ($decimal_notation) to scientific ($scientific_notation)\n\n";

$scientific_notation = "1.23456789e+001";
$decimal_notation = sprintf("%.10g", $scientific_notation);

print "Scientific ($scientific_notation) to decimal ($decimal_notation)\n\n";

generates this output:

Decimal (3.33333333333333) to scientific (3.333333e+000)

Scientific (1.23456789e+001) to decimal (12.3456789)
like image 55
Kurt W. Leucht Avatar answered Nov 12 '22 12:11

Kurt W. Leucht


On a related theme, if you want to convert between decimal notation and engineering notation (which is a version of scientific notation), the Number::FormatEng module from CPAN is handy:

use Number::FormatEng qw(:all);
print format_eng(1234);     # prints 1.234e3
print format_pref(-0.035);  # prints -35m
unformat_pref('1.23T');     # returns 1.23e+12
like image 35
toolic Avatar answered Nov 12 '22 14:11

toolic