I am trying to format numbers with a fixed number of digits before the decimal point.
My understanding is that:
( 3.1 ).format("%02.1f")
Should return a string "03.1". However it returns "3.1".
Any idea what I could be doing wrong?
I am trying to format numbers with a fixed number of digits before the decimal point.
My understanding is that:
( 3.1 ).format("%02.1f")
Should return a string "03.1". However it returns "3.1".
Any idea what I could be doing wrong?
The width specifier in a printf-style format string - in this case, 2 - refers to all the characters, not just the characters to the left of the decimal point.
You need to use a width of 4 to get the desired result:
System.println((3.1).format("%04.1f")); // prints "03.1"
The format string isn't really documented so well in the CIQ API docs.
This resource might be a bit better:
https://cplusplus.com/reference/cstdio/printf/
width - (number) - Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
[for anyone else reading, the 0 flag changes the padding from blank spaces to zeroes]
You may also find this site useful:
https://zhxnlai.github.io/printf/#/ (Printf Format String Visualizer)
Thanks, that worked!