help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Converting an Integer into Human Readable String


From: Thierry Volpiatto
Subject: Re: Converting an Integer into Human Readable String
Date: Sat, 09 Apr 2011 07:24:00 +0200
User-agent: Gnus/5.110016 (No Gnus v0.16) Emacs/23.3.50 (gnu/linux)

Eli Zaretskii <eliz@gnu.org> writes:

>> From: Thierry Volpiatto <thierry.volpiatto@gmail.com>
>> Date: Fri, 08 Apr 2011 21:12:35 +0200
>> 
>> The result you obtain is not what is expected (i.e same than
>> ls -lh)
>> 
>> --8<---------------cut here---------------start------------->8---
>> ls -l .VirtualBox/Machines/LoseDows.vdi
>> -rw------- 1 thierry thierry 7141892608 2011-04-07 08:51 
>> .VirtualBox/Machines/LoseDows.vdi
>> 
>> ls -lh .VirtualBox/Machines/LoseDows.vdi
>> -rw------- 1 thierry thierry 6,7G 2011-04-07 08:51 
>> .VirtualBox/Machines/LoseDows.vdi
>> 
>> (file-size-human-readable 7141892608.0)
>> "7G"
>
> Well, that's what ls-lisp.el was always doing.  But since you asked
> for it, here you go (will commit as soon as Savannah is fixed):
>
> (defun file-size-human-readable (file-size &optional flavor)
>   "Produce a string showing FILE-SIZE in human-readable form.
>
> Optional second argument FLAVOR controls the units and the display format:
>
>  If FLAVOR is nil or omitted, each kilobyte is 1024 bytes and the produced
>     suffixes are \"k\", \"M\", \"G\", \"T\", etc.
>  If FLAVOR is `si', each kilobyte is 1000 bytes and the produced suffixes
>     are \"k\", \"M\", \"G\", \"T\", etc.
>  If FLAVOR is `iec', each kilobyte is 1024 bytes and the produced suffixes
>     are \"KiB\", \"MiB\", \"GiB\", \"TiB\", etc."
>   (let ((power (if (or (null flavor) (eq flavor 'iec))
>                  1024.0
>                1000.0))
>       (post-fixes
>        ;; none, kilo, mega, giga, tera, peta, exa, zetta, yotta
>        (list "" "k" "M" "G" "T" "P" "E" "Z" "Y")))
>     (while (and (>= file-size power) (cdr post-fixes))
>       (setq file-size (/ file-size power)
>           post-fixes (cdr post-fixes)))
>     (format (if (> (mod file-size 1.0) 0.05)
>               "%.1f%s%s"
>             "%.0f%s%s")
>           file-size
>           (if (and (eq flavor 'iec) (string= (car post-fixes) "k"))
>               "K"
>             (car post-fixes))
>           (if (eq flavor 'iec) "iB" ""))))

(file-size-human-readable 7141892608.0)
"6.7G"

Nice, thanks.

-- 
A+ Thierry
Get my Gnupg key:
gpg --keyserver pgp.mit.edu --recv-keys 59F29997 




reply via email to

[Prev in Thread] Current Thread [Next in Thread]