Java floating point number in comma instead of dot

masiboo :

All I have a floating point number in Finnish local. It is like the following:-

  String numberString = "1000,30";
  if(numberString.contains(",")){
        numberString = numberString.replaceAll(",",".").trim();    
    }

    try {
        Number number = Double.parseDouble(numberString);
        return number;
    }catch (NumberFormatException ex){
        System.out.printf(ex.getMessage());
    }
    return null;

But this number has value 1000.30. I would like the number should I have value 1000,30. How can I have Number with the comma instead of the dot? This is a basic question it must have been asked earlier. But all I find is in String data type. I don't see any Number data type.

Lino :

When seeing your comment that the API accepts only Number and that it calls Number#toString() on it, then I see only 1 way to enforce the rightful display. By using your own implementation of Number and overwriting the way Object#toString() works:

public class CorrectlyDisplayedDouble extends Number{
    private final Double internal;

    public CorrectlyDisplayedDouble(Double internal){
        this.internal = internal;
    }

    public int intValue(){
        return internal.intValue();
    }

    public long longValue(){
        return internal.longValue();
    }

    public float floatValue(){
        return internal.floatValue();
    }

    public double doubleValue(){
        return internal.doubleValue();
    }

    public String toString(){
        // replaces periods with commas
        return internal.toString().replace(".", ",");
    }
}

Which can then be easily created using following snippet, which then also can be passed to your third party API:

Number number = new CorrectlyDisplayedDouble(Double.parseDouble(numberString));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110607&siteId=1