2010-03-19 4 views

Répondre

17

sprintf le tour est joué

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"; 

génère cette sortie:

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

Scientific (1.23456789e+001) to decimal (12.3456789) 
+2

J'ai dû utiliser "% .10f" pour obtenir la valeur décimale, car "g" l'a gardé en notation scientifique. J'utilise Perl v5.10.1 sur Ubuntu. Nice post, merci! – Alan

+1

Je n'ai pas pu obtenir 'sprintf' pour fonctionner, mais' printf' et '% .10f' au lieu de' g' ont bien fonctionné. Perl version 5.14.2. – terdon

3

Sur un thème connexe, si vous voulez convertir entre la notation décimale et engineering notation (qui est une version de la notation scientifique) , le module Number::FormatEng du CPAN est pratique:

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 
Questions connexes