Java 限制GWT中的小数位数?
在纯Java中,我通常会有一个类似下面的函数,用于将给定数字的小数位数限制为Java 限制GWT中的小数位数?,java,math,gwt,numerical-methods,Java,Math,Gwt,Numerical Methods,在纯Java中,我通常会有一个类似下面的函数,用于将给定数字的小数位数限制为decimalCount。但是,根据GWT文档,“GWT不提供日期和数字格式类(如java.text.DateFormat、java.text.DecimalFormat、java.text.NumberFormat和java.TimeFormat)的完全仿真。”“要使以下函数在GWT中工作,您会对其做些什么 public static String getFormatted(double value, int deci
decimalCount
。但是,根据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);
}
在gwt Javadoc中查看(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);
所以这应该对你有用
更新
此方法提供与问题中相同的功能。我继续问最有效的方法,看看那个问题。(很抱歉,这个答案被编辑了这么多-它只是让我感到不安)
公共静态字符串getFormatted(双精度值,整数小数){
StringBuilder编号模式=新StringBuilder(
(小数点计数您可以使用
NumberFormat decimalFormat = NumberFormat.getFormat(".##");
来自GWT库,该库将渲染例如1234.789789到1234.78
您可以在这里找到完整的工作示例:在当前的GWT(2.5、2.6)中,现在有:
private final NumberFormat numberFormat = NumberFormat.getDecimalFormat();
System.out.println(numberFormat.format(myFloat));
编辑:根据请求添加GWT版本您还可以在UiBinder文件中指定十进制格式
总数:
您最好使用“0000000000”。子字符串(0,小数点计数)
(假设小数点计数
介于1和10之间)而不是串联,performance-wise.IMO,最好的方法是将StringBuilder与子字符串组合(如果需要24“0”,然后在附加子字符串(0,4)
之前,首先将一个10个字符长的字符串附加到StringBuilder;或者,将该10个字符长的字符串附加三次,并获取计算出的整个字符串的子字符串(0,24)
)。如果您需要经常在应用程序中使用,请尝试不同的变体并对其进行基准测试!请说明“当前GWT”的版本,这样就不会有任何混淆。只需提示:使用。###您将获得1234.79,而不是1234.78:)。必要时使用数字格式进行舍入。您知道如何使用troncate而不是舍入吗?
private final NumberFormat numberFormat = NumberFormat.getDecimalFormat();
System.out.println(numberFormat.format(myFloat));