tcl格式化固定精度的浮点数

时间:2014-07-11 12:23:05

标签: tcl

# 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-07

有没有办法强制tcl获得像625e-09

这样的结果

2 个答案:

答案 0 :(得分:1)

假设您要将其格式化为最接近的指数,您可以使用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)}])。例如,如果指数为9或更低,$exp >= $a可用于格式化。

ideone demo以上代码中最近的&#39;指数。


对于8.5之前的Tcl版本,请使用pow(10.0,$dif)代替10.0**$dif

答案 1 :(得分:0)

我认为format命令中没有任何内容可以直接帮助您。但是,如果您考虑格式代码略有不同,那么获得您想要的东西可能要容易得多(使用一些字符串操作):

format %#3.6g $number

给出的数字如下:6.25000e-007

这可以更容易解析:

  • 提取指数
  • 确定要移动小数点的位置数
  • 移动它并替换指数

恐怕并非完全直截了当,但它应该是可行的。维基页面http://wiki.tcl.tk/5000可能会给你一些启发。