Chr*_*ell 6 java math gwt numerical-methods
在纯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);
}
Run Code Online (Sandbox Code Playgroud)
Jay*_*com 10
查看GWT Javadoc中的NumberFormat(com.google.gwt.i18n.client.NumberFormat).
我从来没有用过它,但我在那里看到了这个例子:
// 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);
Run Code Online (Sandbox Code Playgroud)
所以这对你有用.
此方法提供与您的问题相同的功能.我继续前进,要求找到最有效的方法,在这里看到这个问题.(对不起,这个答案已经编辑了很多 - 这只是让我烦恼)
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);
}
Run Code Online (Sandbox Code Playgroud)
替代方案包括使用设定数量的"0"并使用子字符串来提取所需的模式,如评论中提到的@Thomas Broyer.
您可以使用
NumberFormat decimalFormat = NumberFormat.getFormat(".##");
Run Code Online (Sandbox Code Playgroud)
来自GWT库,例如1234.789789到1234.78
您可以在此处找到完整的工作示例:http://gwt.google.com/samples/Showcase/Showcase.html#!CwNumberFormat