【问题标题】:How can I convert between scientific and decimal notation in Perl?如何在 Perl 中转换科学记数法和十进制记数法?
【发布时间】:2010-03-19 01:20:55
【问题描述】:

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

【问题讨论】:

    标签: perl decimal notation scientific-notation


    【解决方案1】:

    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)
    

    【讨论】:

    • 我不得不使用 "%.10f" 来获得十进制值,因为 "g" 以科学记数法保存它。我在 Ubuntu 上使用 Perl v5.10.1。不错的帖子,谢谢!
    • 我无法让sprintf 工作,但printf%.10f 而不是g 工作正常。 Perl 版本 5.14.2。
    • @terdon,你是对的。请注意,%.10f 也可以与 sprintf 一起使用。你可以把你的评论变成一个单独的答案吗?
    • @n.r.没必要,基本思路就是用printf家族。我建议进行修改。
    • 与“%.10g”相比,使用“%.10f”的一个区别是该值将在指定的字段大小(在本例中为 10 位)有额外的零:12.3456789000。在格式字符串中使用“g”而不是“f”将省略那些额外的零。
    【解决方案2】:

    在相关主题上,如果您想在十进制表示法和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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 2012-11-29
      相关资源
      最近更新 更多