Java 在 SLF4J 中格式化浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22720865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Formatting floating point numbers in SLF4J
提问by Matthias Braun
I'd like to format my doubles and floats to a certain number of decimal places with SLF4J.
我想用 SLF4J 格式化我的双打和浮动到一定数量的小数位。
Basically, I'm looking for the equivalent of Java's String.format("%.2f", floatValue)
in SLF4J.
基本上,我String.format("%.2f", floatValue)
在 SLF4J 中寻找 Java 的等价物。
Having read through SLF4J's documentation and googling around I couldn't find a hint whether it has that feature.
通读了 SLF4J 的文档并在谷歌上搜索后,我找不到它是否具有该功能的提示。
I'm using slf4j-api:1.7.6
and slf4j-jdk14:1.7.6
我正在使用slf4j-api:1.7.6
和slf4j-jdk14:1.7.6
Any help is much appreciated.
任何帮助深表感谢。
采纳答案by Isaac
I am assuming that you're referring to SLF4J's convention of expanding parameters, e.g.:
我假设您指的是 SLF4J 的扩展参数约定,例如:
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).
所以,答案是否定的。从 SLF4J 1.7.7 开始,您要求做的事情是不可能的,因为 SLF4J 的扩展算法不允许自定义渲染器(例如通过 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_performanceso it's unlikely to change
好吧,
{}
出于性能考虑“仅支持”,当前的格式化实现优于 String.format() 10 倍。 http://www.slf4j.org/faq.html#logging_performance所以不太可能改变
(source)
(来源)
回答by Svullo
A somewhat ugly solution that incurs the creation of a temporary object could be this
导致创建临时对象的有点丑陋的解决方案可能是这样的
public class DelayedFormatter{
String format; Object[] args;
public DelayedFormatter(String format, Object... args){
this.format = format; this.args = args;
}
public static DelayedFormatter format(String format, Object... args){
return new DelayedFormatter(format, args);
}
@Override public String toString(){
return String.format(format, args);
}
}
and then
进而
import static DelayedFormatter.format;
...
logger.debug("v = {}", format("%.03f", v));