Boost logo

Boost :

From: Stefan Slapeta (stefan_at_[hidden])
Date: 2004-09-06 06:19:37


Hi all,

I've recently developed a small lib for custom numeric formatting, which
is part of many programming languages. You pass any number and a format
string which controls the formatting.

Some examples (using the US locale):

num_format ( 3332123.3332, "$#,0.00" ) -> "$3,332,123.33"
num_format ( 123, "#.00" ) -> "123.00"
num_format ( 12, "000" ) -> "012"
num_format ( 12.9, "000" ) -> "013" (rounded!)
num_format ( -123.1, "#.#;-#.00" ) -> "-123.10"
num_format ( -123, "$#;- $0.00;0" ) -> "- $123.00"
num_format ( 0, "0.00;-0.00;<Zero>" ) -> "<Zero>"
num_format ( 1000000, "#,#,.00" ) -> "1,000.00"

Short explanation for the format string:

. marks the decimal separator

, has two functions:
     - if the format string contains any "," before, but not
       immediately before the decimal separator, there will be
       thousand separators in the output.
     - if the format string contains any "," immediately before
       the decimal separator, the number will be divided by the
       number of "," characters multiplied by 1000.

0 If there is no digit in this position, there will be a 0 in
     the output string

# If there is a digit in this position, it is copied to the output
     string (except non-significant zeros)

; Section separator: if there is one section in the format string,
     it applies to all values. If there are two sections, the first
     applies to positive values and to zeros and the second applies
     to negative values. If there are three sections, the first applies
     to positive values, the second to negative values and the third to
     zeros, except if the second section is empty, in which case the
     first section applies to all non-negative values.

Everything in enclosed by ' or " in the format string will be copied to
the output as is.

I've been looking for a (C++) solution for this for a long time and as I
didn't find anything appropriate, I developed it myself finally. If
anybody is interested, I could post source somewhere.

Stefan


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk