This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

Problem with formating units

Help for those learning Tcl or writing their own scripts.
Post Reply
a
aRTiST
Voice
Posts: 4
Joined: Fri Apr 17, 2009 11:01 am

Problem with formating units

Post by aRTiST »

Code: Select all

proc format_1024_units {value} {
	set len [string length $value]
	if {$value < 1024} {
		return [format "%s B" $value]
	} else {
		set unit [expr {($len - 1) / 3}]
		return [format "%.1f %s" [expr {$value / pow(1024,$unit)}] [lindex [list B KB MB GB TB PB EB ZB YB] $unit]]
	}
}
But the result is then often 0.0TB (value is really 35.2GB unformated).

Any hints where im doing wrong ?

TIA arti
User avatar
speechles
Revered One
Posts: 1398
Joined: Sat Aug 26, 2006 10:19 pm
Location: emerald triangle, california (coastal redwoods)

Post by speechles »

The problem here is your method of attaining size doesn't match throughout your procedure. You initially set "len" to the [string length $value]. Then you set "unit" to to "($len-1) / 3". This where you make your mistake. This assumes 1,000 for our divisor. Yet below that you make use of the correct 1,024 to raise powers which throws off the entire equation. Using the method below should solve your problem and its more compact.

Code: Select all

proc format_1024_units {value} { 
	set test $value ; set unit 0
	while {[set test [expr {$test / 1024}]] > 0} {
		incr unit
	}
	return [format "%.1f %s" [expr {$value / pow(1024,$unit)}] [lindex [list B KB MB GB TB PB EB ZB YB] $unit]]
}
a
aRTiST
Voice
Posts: 4
Joined: Fri Apr 17, 2009 11:01 am

hm

Post by aRTiST »

I tried with ur version, but now ill get an error :

Code: Select all

floating-point value too large to represent
:/
n
nml375
Revered One
Posts: 2860
Joined: Fri Aug 04, 2006 2:09 pm

Post by nml375 »

Could you verify that $value is indeed an integer and not a float?

The code posted by speechles relies on integer division, and will fail if either the nominator or the denominator is a float. I'd also recommend adding a constraint to the value of unit, as to prevent it from going out of bounds for the "suffix-list".
You might be able to get away with forcing $test to an integer in the beginning.
NML_375
Post Reply