Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 510
Matthias Braun Avatar asked Mar 28 '14 18:03

Matthias Braun


People also ask

How do you show float to 2 decimal places?

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 (%).

How do you do 2 decimal places in Java?

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.

What is used to format a floating point number in Java?

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.

How do you format a float in Python?

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.


1 Answers

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)

like image 177
Isaac Avatar answered Oct 01 '22 05:10

Isaac