Formatting floating point numbers in SLF4J

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.


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)


A somewhat ugly solution that incurs the creation of a temporary object could be this

public class DelayedFormatter {
    public static Object format(String format, Object... args) {
        return new Object() {
            @Override
            public String toString() {
                return String.format(format, args);
            }
        };
    }
}

and then

import static DelayedFormatter.format;
...
logger.debug("v = {}", format("%.03f", v));