Can I align a list of currency values on the decimal points using sprintf?
I hate sprintf. I've never been able to learn the syntax for whatever reason. My brain just won't absorb it.
sprintf questionCan I align a list of currency values on the decimal points using sprintf?
I hate sprintf. I've never been able to learn the syntax for whatever reason. My brain just won't absorb it. Short answer: yes. Off the top of my head it'd be something like sprintf('%5.2f', $number) -- that'd pad up to five digits to the left of the decimal with spaces, give you 2 digits after, and right align it -- but it's one of those things I almost always have to look up, or end up rolling my own functions that work in a way more conducive to my method of thinking. (I'm also assuming PHP, but AFAIK [s]printf is one of those C/Java/PHP/whatever impkementations that's pretty standard.)
Also bear in mind I've not eaten for >48 hours and consumed several beers this evening whilst sitting through a frankly appalling amateur pantomime, so I may be talking through my hat...
I think you can, but you'd best look it up in a reference. I don't think Mat is quite right, since the number after the % is always the total field width. Thus %5.2f means total width 5, decimal places 2.
What you most likely need is decimal places 2, always displayed; in other words you need 752.00 rather than 752, which you might otherwise get. You need the flags for always showing the decimal point and right padding with zeros. I forget how to do it without looking it up myself. This is how to do it in a real language like C++.
From http://www.arachnoid.com/cpptutor/student3.html : This is an advanced topic, because displaying currency is more complex than it may appear at first sight. There is an advanced C++ feature called "locale" that can handle this problem in a powerful way, but it is not enabled on many compilers (and not yet on the very common compiler I have chosen for this tutorial). Here is a way to display currency: #include <iostream> #include <iomanip> #include <string> using namespace std; void showCurrency(double dv, int width = 14) { const string radix = "."; const string thousands = ","; const string unit = "$"; unsigned long v = (unsigned long) ((dv * 100.0) + .5); string fmt,digit; int i = -2; do { if(i == 0) { fmt = radix + fmt; } if((i > 0) && (!(i % 3))) { fmt = thousands + fmt; } digit = (v % 10) + '0'; fmt = digit + fmt; v /= 10; i++; } while((v) || (i < 1)); cout << unit << setw(width) << fmt.c_str() << endl; } int main() { double x = 12345678.90; while(x > .001) { showCurrency(x); x /= 10.0; } return 0; } |
|
|
|
|