I have some string values that I need to convert to float while preserving two decimal places. I am using GWT so all the examples I try dont work in GWT 2.7
String value = "00.00";
String value2 = "-34.90";
String value3 = "3.45";
How can I convert string to float with 2 decimal places in GWT?
GWT is a framework and you don't "convert" strings to floats in GWT but in Java.
As already stated in comments, you can't ask for a specific precision in float or double . You also can't trust that their String
representation is their actual value...
If you really need only two decimals to represent a number, I suggest you use an int
that gets the value times 100, then perform the simple arithmetics anywhere you need. You can wrap it in a Number
class:
class TwoDecimal extends Number {
protected int val;
public TwoDecimal(double val) {
this.val = (int)Math.round(100 * val);
}
@Override
public double toDouble() {
return val / 100.0;
}
// Implement other abstract toXXX() methods
@Override
public String toString() {
return (val / 100) + "." + (val % 100);
}
}
Also keep in mind that an int
might not be able to store the span a double
covers, so you should adapt it to your use-case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.