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.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Kurt W. Leucht
  • 4,725
  • 8
  • 33
  • 45

2 Answers2

18

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)
toolic
  • 57,801
  • 17
  • 75
  • 117
Kurt W. Leucht
  • 4,725
  • 8
  • 33
  • 45
  • 3
    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! – Alan Mar 19 '12 at 16:27
  • 3
    I couldn't get `sprintf` to work but `printf` and `%.10f` instead of `g` worked fine. Perl version 5.14.2. – terdon Dec 19 '13 at 13:21
  • 1
    @terdon, you're right. Notice that `%.10f` works with `sprintf` as well. You could make your comment into a separate answer maybe? – n.r. Jun 19 '18 at 14:55
  • @n.r. no need, the basic idea is to use the printf family. I suggested an edit instead. – terdon Jun 19 '18 at 15:01
  • 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. – Trutane Feb 27 '19 at 20:16
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
toolic
  • 57,801
  • 17
  • 75
  • 117