2010-03-19 34 views

Trả lời

17

sprintf hiện các 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"; 

tạo ra sản lượng này:

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

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

Tôi phải sử dụng "% .10f" để lấy giá trị thập phân, vì "g" giữ nó trong ký pháp khoa học. Tôi đang sử dụng Perl v5.10.1 trên Ubuntu. Nice post, cảm ơn! – Alan

+1

Tôi không thể nhận 'sprintf' để hoạt động nhưng' printf' và '% .10f' thay vì' g' hoạt động tốt. Perl phiên bản 5.14.2. – terdon

3

Trên một chủ đề có liên quan, nếu bạn muốn chuyển đổi giữa ký hiệu thập phân và engineering notation (mà là một phiên bản của ký hiệu khoa học) , mô-đun Number::FormatEng từ CPAN tiện dụng:

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 
Các vấn đề liên quan