Add thousands separators to numbers

If you have a cool piece of software to share, but you are not hosting it officially yet, please dump it in here. If you have code snippets that are useful, please donate!
Post Reply
ssigala
Earned some good credits
Earned some good credits
Posts: 109
Joined: Fri Sep 03, 2004 9:30 am
Location: Brescia, Italy

Add thousands separators to numbers

Post by ssigala » Sun Aug 14, 2005 1:56 pm

A quick and dirty function for adding thousands separators to integers.
The separator is:
  • the comma "," for locales where the dot is used as decimal separator (e.g. US)
  • the dot "." for locales where the comma is used as decimal separator (e.g. IT, FR)
Example of application:

Code: Select all

int mynumber = 12345678;
wxString s = wxString::Format("%d", mynumber); // format the integer to string
s = FormatThousands(s); // add separators
// s now contains "12,345,678" or "12.345.678" according to locale.
Code:

Code: Select all

wxString FormatThousands(const wxString& s)
{
	static wxString thousandssep = _T(",");
	static struct lconv *loc = 0;
	if (!loc) {
		loc = localeconv();
		if (loc) thousandssep = loc->thousands_sep;
	}

	wxString in = s, out;
	while (in.Length() > 3) {
		out.Prepend(thousandssep + in.Right(3));
		in.RemoveLast(3);
	}
	if (!in.IsEmpty())
		out.Prepend(in);
	return out;
}
Edit: reformatted a bit the post
Last edited by ssigala on Tue Aug 23, 2005 2:57 pm, edited 1 time in total.
Sandro Sigala - Kynosoft, Brescia

Jorg
Moderator
Moderator
Posts: 3971
Joined: Fri Aug 27, 2004 9:38 pm
Location: Delft, Netherlands
Contact:

Post by Jorg » Sun Aug 14, 2005 2:01 pm

Very nice! Could come in handy when I am going to work on my cashrunner again. A prg to list all of my banking stuff in categories, where I will see how much I spent per month :-)
Forensic Software Engineer
Netherlands Forensic Insitute
http://english.forensischinstituut.nl/
-------------------------------------
Jorg's WasteBucket
http://www.xs4all.nl/~jorgb/wb

daddydave
Filthy Rich wx Solver
Filthy Rich wx Solver
Posts: 214
Joined: Wed Jun 15, 2005 3:31 am
Location: United States
Contact:

Post by daddydave » Thu Aug 25, 2005 7:53 pm

Great idea.

A small suggestion, maybe add "lakh" (100000) and "crore" (10000000) support. I think in India-Pakistan, 3 million would be written, from what I understand, 30,00,000 (meaning 30 lakh).

http://www.absoluteastronomy.com/encycl ... a/lakh.htm
http://www.absoluteastronomy.com/encycl ... system.htm

I used to see news examples of this, but a quick check of online news sites found only articles that use Engliish thousands separators. Maybe this is falling out of fashion?

Post Reply