I want to produce a (non-localized) string representing a double to 'n' decimal places, preferably rounded up. E.g. to four decimal places, 1.234567
-> "1.2346"
I know I can do this with BigDecimal
, DecimalFormat
or String.format()
, but in my project I'm constrained and not able to use them or any third-party library. Is it possible to write a simple function to do it? How?
Update (more detail): The reason for this question is that I want a solution that uses identical code in GWT and in Java, and requires a minimal amount of code and libraries. It is vital that the number as formatted does not change based on the browser's locale (E.g. I don't want "1,2346"
when a French user runs it).
In GWT, I have written this Javascript wrapper function:
/**
* Convert a double to a string with a specified number of decimal places.
* The reason we need this function is that by default GWT localizes
* number formatting.
*
* @param d double value
* @param decimalPlaces number of decimal places to include
* @return non-localized string representation of {@code d}
*/
public static native String toFixed(double d, int decimalPlaces) /*-{
return d.toFixed(decimalPlaces);
}-*/;
I want to replace it with some simple Java, so I can use the same code on both client and server.
public static String toFixed(double d, int decimalPlaces) {
// TODO
}