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: Eli Zaretskii
Subject: Re: Converting an Integer into Human Readable String
Date: Fri, 08 Apr 2011 18:19:01 +0300

> From: "Pascal J. Bourguignon" <pjb@informatimago.com>
> Date: Fri, 08 Apr 2011 13:41:30 +0200
> 
> Instead, you could have had some fun, and implement yourself the
> required function.   Well, now you've got only what you merit, here I
> had all the fun, you can have the function:
> 
>     (format-human-readable-big-number 123456789012
>                                       *normal-format*
>                                       *exceptional-format*
>                                        "B" t :binary)
>     --> "  114.978 GiB"
> 
> 
> Now, you may call this function in the places of interest in emacs.

Wow!  I've just installed in Emacs a much more modest variant
(reproduced below for those who don't live on the bleeding edge).

(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 "%.0f%s%s" file-size
            (if (and (eq flavor 'iec) (string= (car post-fixes) "k"))
                "K"
              (car post-fixes))
            (if (eq flavor 'iec) "iB" ""))))



reply via email to

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