在纯 Java 中,我通常会使用如下所示的函数来将小数位数限制为decimalCount
对于给定的数字value
。但是,根据 GWT 文档,“GWT 不提供对日期和数字格式化类(例如 java.text.DateFormat、java.text.DecimalFormat、java.text.NumberFormat 和 java.TimeFormat)的完整模拟。”为了使其在 GWT 中工作,需要对以下函数执行什么操作?
public static String getFormatted(double value, int decimalCount) {
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMaximumFractionDigits(decimalCount);
return decimalFormat.format(value);
}
查看数字格式 http://www.gwtproject.org/javadoc/latest/com/google/gwt/i18n/client/NumberFormat.html(com.google.gwt.i18n.client.NumberFormat) 在 GWT Javadoc 中。
我从未使用过它,但我在那里看到了这个例子:
// Custom format
value = 12345.6789;
formatted = NumberFormat.getFormat("000000.000000").format(value);
// prints 012345.678900 in the default locale
GWT.log("Formatted string is" + formatted);
所以这应该对你有用。
Update
此方法提供与您问题中的功能相同的功能。我继续询问最有效的方法来解决这个问题,请参阅该问题here https://stackoverflow.com/questions/7226623/most-efficient-way-to-fill-a-string-with-a-specified-length-with-a-specified-char/7226643#7226643。 (抱歉,这个答案已经被编辑了这么多 - 这只是困扰我)
public static String getFormatted(double value, int decimalCount) {
StringBuilder numberPattern = new StringBuilder(
(decimalCount <= 0) ? "" : ".");
for (int i = 0; i < decimalCount; i++) {
numberPattern.append('0');
}
return NumberFormat.getFormat(numberPattern.toString()).format(value);
}
替代方案包括使用一定数量的“0”并使用子字符串来提取所需的模式,如@Thomas Broyer 在评论中提到的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)