4 ms·
My contribution to an example of something done right in the first FORTRAN and then done wrong many times afterwards: "The March of Progress > * 1956: Fortran
by acqq 7y ago
My contribution to an example of something done right in the first FORTRAN and then done wrong many times afterwards:
"The March of Progress
> * 1956: Fortran I:
> PRINT 1, X
> 1 FORMAT (F10.2)
* 1980: C
printf("%10.2f", x);
* 1988: C++
cout << setw(10) << setprecision(2) << showpoint << x;
* 1996: Java
java.text.NumberFormat formatter = java.text.NumberFormat.getNumberInstance(); formatter.setMinimumFractionDigits(2); formatter.setMaximumFractionDigits(2); String s = formatter.format(x); for (int i = s.length(); i < 10; i++) System.out.print(' '); System.out.print(s);
* 2004: Java
System.out.printf("%10.2f", x);
* 2008: Scala and Groovy
printf("%10.2f", x)
"
The reference and the details (2012):
https://news.ycombinator.com/item?id=3964475 https://news.ycombinator.com/item?id=3964475
- nwallin 7y agoIn my work life, I have a problem where I have to interface with a stringly typed API. For instance, characters 20-25 in a 400 byte string are a floating point number. No it's not a good API but I don't make decisions. So you need a six character float. "12" is wrong because it's two characters, also "12<four spaces>" is invalid. "1.2e01" is wrong compared to "12.000" because it has (many) more significant digits. ".00001" is wrong compared to "1.2e-5". I don't know how to solve this problem. printf doesn't cut it. It simply can't specify an exact number of characters.
- BeeOnRope 7y agoYou could try: %06.*g for width 6 down to 1. I believe this will always find an answer, and the one with the largest number of significant digits. For example: void format(double val, int width, char* buf) { for (int w = width; w > 0; w--) { int count = sprintf(buf, "%06.*g", w, val); if (count == width) return; } } "Working" example (unsafe, exits on failure, etc): https://godbolt.org/z/WiaPkT https://godbolt.org/z/WiaPkT Note that you can't represent negative values equal or below -1e-100 since those take 7 characters.