Search code examples
javanumber-formatting

how to take same formate out put 2.5 and 2,5?


Input can be given both way in my software, when I give 2.5 , it return 2.5. but whem I given 2,5 it give me, 2.0 . This is my code ;

 public PrescriptionNotationParser()
  {
    final NumberFormat numberFormat = NumberFormat.getInstance();

    if (numberFormat instanceof DecimalFormat)
    {
      doseValueFormat = (DecimalFormat) numberFormat;
      doseValueFormat.applyPattern("##.########");
      decimalFormatSymbols = doseValueFormat.getDecimalFormatSymbols();
    }
  }

  private double parse(final String valueStr)
  {
   try
    {
      return doseValueFormat.parse(valueStr).doubleValue();
   }
  catch (ParseException e)
  {
    return 0;
   }
}

Expect some expertise help to resolve this issue ?


Solution

  • 2.5 is a float, but 2,5 isn't float format, so 2,5 will only get the previous value 2.

    If you want support 2,5 to 2.5

    private double parse(String valueStr)//remove final
      {
       try
        {
          //replace valueStr "," to "."
          return doseValueFormat.parse(valueStr.replace(",", ".")).doubleValue();
       }
      catch (ParseException e)
      {
        return 0;
       }
     }
    

    If you want 23,000 .50 to 23000.5, only remove , and space.
    a float . only one at most.

    private double parse(String valueStr)//remove final
      {
       try
        {
          //valueStr remove all "," and " "
          return doseValueFormat.parse(valueStr.replaceAll(",| ", "")).doubleValue();
       }
      catch (ParseException e)
      {
        return 0;
       }
     }