Numbers formatting with printf
Hello there! I'm another Java newbie, and I was just wondering what the magic formula was to make printf spew out my numbers like so:
1 565 434 with a space for every 10^3;10^6;10^9..etc instead of 1565434 and alternatively, how do I achieve the following:
1,565,434.0 (<-- doesnt matter in this case for decimals, was just to show comma's versus dots. in the case Im using this all i ever get are integers so I wont even be getting the " . " notation in my results)
thanks a lot!
K
Re: Numbers formatting with printf
Try the DecimalFormat class.
Re: Numbers formatting with printf
ok, now how do you do the first notation? i got it to put comma's at every 3 step, but its not the same system for spaces apparently. its disregarding the formatting I'm 'showing' it.
K
Re: Numbers formatting with printf
Yeah. I wasn't sure myself, tested it and got the same results. Unless someone else has a better suggestion you probably will have to do the formatting yourself. It shouldn't be that hard.
Re: Numbers formatting with printf
next quick question, still about same topic.
if i want printf to align output on the right of 10 spaces, in the case of double values displayed as integers, i'd write printf("%10d",value1);
but, how do I get to the do the same for an object? in the case of DecimalFormat?
for it to work you need to make an object of class DecimalFormat and use that object's format method in as argument. So
printf(DecimalFormatObj.format(value1)); works fine, but not
printf("%10d",DecimalFormatObj.format(value1)). I know it might look dumb to be double formatting and thats why I was hoping printf had a formula to output things as 1,000.0
Thanks a lot for the help!
K
Re: Numbers formatting with printf
Quote:
I know it might look dumb to be double formatting and thats why I was hoping printf had a formula to output things as 1,000.0
I am partial to printf() and certainly it will put in commas (or the locale default thousands separator), align how you want, and round to any desired number of decimal places. See, eg, reply #6 in this recent thread.
Re: Numbers formatting with printf
Awesome thanks ! xD I just like how printf facilitates 'generic' formatting when you get lots of lines of output with misc numbers )
but, do you know how to get integers, type double for bigness^^, displayed with " " -spaces- instead of the comma's for exact same case as previous. im aiming at:
10 000.0 for 10^4
much obliged !
K
Re: Numbers formatting with printf
DecimalFormat is more flexible about the pattern to be used. As far as I know the only options for printf() etc are for thousands not to be separated at all, or to be separated by whatever the locale says is the thousands separator. (Eg , in the US or NZ).
You could use String.format() then replace commas with spaces, but that's a bit yukky really.