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

2

9

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.

Anew answered 19/3, 2010 at 1:20 Comment(0)
A
19

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)
Anew answered 19/3, 2010 at 1:21 Comment(5)
I had to use "%.10f" to get the decimal value, as "g" kept it in scientific notation. I'm using Perl v5.10.1 on Ubuntu. Nice post, thanks!Wherewith
I couldn't get sprintf to work but printf and %.10f instead of g worked fine. Perl version 5.14.2.Madrigal
@terdon, you're right. Notice that %.10f works with sprintf as well. You could make your comment into a separate answer maybe?Leavings
@Leavings no need, the basic idea is to use the printf family. I suggested an edit instead.Madrigal
One difference with using "%.10f" compared to "%.10g" is that the value will have additional zeros out to the specified field size (10 digits in this case): 12.3456789000. Using "g" instead of "f" in the format string will omit those extra zeros.Tel
G
3

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
Giuseppe answered 19/3, 2010 at 2:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.