Limit decimal places in GWT?

In pure Java, I would usually have a function like the one below to limit the number of decimal places to decimalCount for a given number value . However, according to the GWT docs, "GWT does not provide full emulation for date and number formatting classes (such as java.text.DateFormat, java.text.DecimalFormat, java.text.NumberFormat and java.TimeFormat)." What can be done with the following function to make it work in GWT?

 public static String getFormatted(double value, int decimalCount) { DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(decimalCount); return decimalFormat.format(value); } 
+6
source share
4 answers

Check the NumberFormat (com.google.gwt.i18n.client.NumberFormat) in the GWT Javadoc.

I have never used it, but I see this example:

 // 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); 

So this should work for you.

Update

This method provides the same functionality as in your question. I went ahead and asked for the most efficient way, see this question here . (Sorry this answer has been edited so much - it just listened to me)

 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); } 

Alternatives include using the specified amount of "0" and using a substring to extend the desired pattern as the @Thomas Broyer mentioned in the comments.

+9
source

you can use

 NumberFormat decimalFormat = NumberFormat.getFormat(".##"); 

from the GWT library, which will display, for example, 1234.789789 to 1234.78

Here you can find the full working example: http://gwt.google.com/samples/Showcase/Showcase.html#!CwNumberFormat

+8
source

The current GWT (2.5, 2.6) now has:

 private final NumberFormat numberFormat = NumberFormat.getDecimalFormat(); System.out.println(numberFormat.format(myFloat)); 

Edit: Added GWT versions for request

+1
source

You can also specify the decimal format in the UiBinder file

 <g:HTMLPanel ui:field="grid"> <table> <tr> <td> <g:Label> <ui:msg description="total">Total:</ui:msg> </g:Label> </td> <td> <g:NumberLabel customFormat="0.00" ui:field="total"/> </td> </tr> </table> </g:HTMLPanel> 
+1
source

Source: https://habr.com/ru/post/896034/


All Articles