s c h e m a t i c s : c o o k b o o k

/ WebHome / TOC / NumberChapter / Cookbook.NumberRecipeCommas

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Putting Commas in Numbers

Problem

You need to format a number for printing with commas (or other locale-dependant marks) in the appropriate places. This is important for creating human-legible print copies of reports.

Solution

Use the Perl-compatible regular expression engine to insert the commas where needed. It's simplest to reverse the string prior to the regexp-pass so that we can hop over any decimal portion. Then reverse the string back on return.

(require (lib "13.ss" "srfi")
         (lib "pregexp.ss" "mzlib"))

(define (partition-number number separator)
  (let ((num (string-reverse (number->string number)))
        (re (pregexp "(\\d\\d\\d)(?=\\d)(?!\\d\\.)"))
        (repl (string-append "\\1" separator)))
    (string-reverse (pregexp-replace* re num repl))))

Discussion

While this function works, it would be better if it checked the types of its input arguments to deal with the case of an input string, or someone passing the separator parameter as a character (rather than a string).

It would also be better if a version was available that only partitioned numbers the decimal point, although this is easy enough to implement with regular expressions. Ie: I would usually rather have a result of 1,928,828.12345 than 1,928,828.12,345.

Here's an example of partition-number in action:

> (partition-number 1918928282 ",")
"1,918,928,282"
> (partition-number 1982928828 "'")
"1'982'928'828"
> (partition-number 1982928828.12345 "'")
"1'982'928'828.12'345"

See Also

Mastering Regular Expressions, Chapter 7, section "Adding Commas to a Number"

CookbookForm
TopicType: Recipe
ParentTopic: NumberRecipes
TopicOrder: 140

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest