# the unit of period is picosecond
set period 625000.0
set period_sec [format %3.6g [expr $period * 1e-12]]
puts $period_sec
結果:6.25e-07TCL格式化浮點
有沒有辦法迫使TCL獲得像625E-09
# the unit of period is picosecond
set period 625000.0
set period_sec [format %3.6g [expr $period * 1e-12]]
puts $period_sec
結果:6.25e-07TCL格式化浮點
有沒有辦法迫使TCL獲得像625E-09
假設你希望把它格式化到最近的指數,你可以使用一個proc
哪些格式是這樣的:
proc fix_sci {n} {
# Not a sci-fmt number with negative exponent
if {![string match "*e-*" $n]} {return $n}
# The set of exponents
set a 9
set b 12
# Grab the number (I called it 'front') and the exponent (called 'exp')
regexp -- {(-?[0-9.]+)e-0*([0-9]+)} $n - front exp
# Check which set of exponent is closer to the exponent of the number
if {[expr {abs($exp-$a)}] < [expr {abs($exp-$b)}]} {
# If it's the first, get the difference and adjust 'front'
set dif [expr {$exp-$a}]
set front [expr {$front/(10.0**$dif)}]
set exp $a
} else {
# If it's the first, get the difference and adjust 'front'
set dif [expr {$exp-$b}]
set front [expr {$front/(10.0**$dif)}]
set exp $b
}
# Return the formatted numbers, front in max 3 digits and exponent in 2 digits
return [format %3ge-%.2d $front $exp]
}
請注意,您原有的代碼返回6.25e-007
(3個位數指數)。
如果您需要更改規則或舍入指數,則必須更改if
部分(即[expr {abs($exp-$a)}] < [expr {abs($exp-$b)}]
)。例如$exp >= $a
可以用來格式化指數爲9或以下的格式。
ideone demo上面代碼爲'最接近'的指數。
爲TCL 8.5版本之前,使用的pow(10.0,$dif)
代替10.0**$dif
你的proc爲我工作,非常感謝 –
@TigranKhachikyan真棒!另外,看到了你的其他評論,你可以簡化它只獲得e-09/e-12只使用'如果'和選擇你需要的一個(無論是'a'還是'b'),如果你需要這兩者中的任何一個。 – Jerry
我不認爲這有什麼的結果格式化命令,這將直接幫助你。但是,如果考慮對格式代碼略有變化,那麼它可能是一個更容易得到你想要的東西(有位字符串操作):
format %#3.6g $number
給出了一個數字,如:6.25000e-007
這可以更容易地解析:
這不是完全直截了當,但我認爲它應該是可行的。維基頁面http://wiki.tcl.tk/5000可能會給你一些啓發。
我想要的結果無論是在E-09或E-12 –
A排序的工程符號的東西?好問題;想不到任何簡單的事情(而且我將在一天的其餘時間裏失去互聯網,所以不能找出更復雜的東西......) –
如果你的結果是'6.25e-10',應該怎麼辦? ?它應該成爲'e-09'還是'e-12'? (基本上,總是指數上下或最接近的一個? – Jerry