I'd like to format my doubles and floats to a certain number of decimal places with SLF4J.
Basically, I'm looking for the equivalent of Java's String.format("%.2f", floatValue)
in SLF4J.
Having read through SLF4J's documentation and googling around I couldn't find a hint whether it has that feature.
I'm using slf4j-api:1.7.6
and slf4j-jdk14:1.7.6
Any help is much appreciated.
The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.
By the way there are numerous way to format numbers in Java, you can use either DecimalFormat class, or NumberFormat or even Formatter class to format floating point numbers in Java.
In Python, there are various methods for formatting data types. The %f formatter is specifically used for formatting float values (numbers with decimals). We can use the %f formatter to specify the number of decimal numbers to be returned when a floating point number is rounded up.
I am assuming that you're referring to SLF4J's convention of expanding parameters, e.g.:
float f; ... logger.debug("My number is {}", f);
So, the answer is no. As of SLF4J 1.7.7, what you're asking to do is impossible as SLF4J's expansion algorithm doesn't allow for custom renderers (such as the one available via Log4J).
Seems worthy of a feature request, though.
EDIT:
Well,
{}
is "only supported" for performance considerations, current formatting implementation outperforms String.format() at 10 times. http://www.slf4j.org/faq.html#logging_performance so it's unlikely to change
(source)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With