【发布时间】:2010-03-19 01:20:55
【问题描述】:
我知道这完全是一个新手问题,但对于许多新程序员来说,答案可能并不明显。最初对我来说并不明显,所以我在 Internet 上搜索 Perl 模块来完成这个简单的任务。
【问题讨论】:
标签: perl decimal notation scientific-notation
我知道这完全是一个新手问题,但对于许多新程序员来说,答案可能并不明显。最初对我来说并不明显,所以我在 Internet 上搜索 Perl 模块来完成这个简单的任务。
【问题讨论】:
标签: perl decimal notation scientific-notation
sprintf 成功了
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";
产生这个输出:
Decimal (3.33333333333333) to scientific (3.333333e+000)
Scientific (1.23456789e+001) to decimal (12.3456789)
【讨论】:
sprintf 工作,但printf 和%.10f 而不是g 工作正常。 Perl 版本 5.14.2。
%.10f 也可以与 sprintf 一起使用。你可以把你的评论变成一个单独的答案吗?
12.3456789000。在格式字符串中使用“g”而不是“f”将省略那些额外的零。
在相关主题上,如果您想在十进制表示法和engineering notation(这是科学记数法的一个版本)之间进行转换,CPAN 的Number::FormatEng 模块很方便:
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
【讨论】: