代码之家  ›  专栏  ›  技术社区  ›  Kurt W. Leucht

如何在Perl中在科学和十进制符号之间进行转换?

  •  6
  • Kurt W. Leucht  · 技术社区  · 15 年前

    我知道这是一个全新的问题,但对于许多新程序员来说答案可能并不明显。最初对我来说并不明显,所以我在互联网上搜索Perl模块来完成这个简单的任务。

    2 回复  |  直到 11 年前
        1
  •  18
  •   toolic    15 年前

    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)
    
        2
  •  3
  •   toolic    11 年前

    在相关主题中,如果要在十进制表示法和 engineering notation (这是科学记数法的一个版本) Number::FormatEng 来自CPAN的模块很方便:

    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
    
    推荐文章