Search code examples
javaspringstringgetfloating-point

How transfer Float number due to HTTP GET request?


Could you help me with my issue? I have a back-end on Java Spring Boot and I need to use GET request to transfer for example "2300,55". As I understand the GET only can transfer Strings and with Long numbers where was no problems yet, but I need to transfer number with comma or with point. How to do this?

I tried to parse it, getting String and parse in try/catch block:

...
    @PathVariable("weight") String weight
    try {
        float parsedWeight = Float.parseFloat(weight);
    } catch (NumberFormatException e) {
...

And catched

java.lang.NumberFormatException: For input string: "2300,55"

But if I try it with point in stead of comma "2300.55" it's persisted OK into database, but it's became just "2300". Database PostgreSQL and column type is REAL -> that is float4 (a single-precision floating-point number (4 bytes))


Solution

  • And catched java.lang.NumberFormatException: For input string: "2300,55"

    The issues like having decimal comma instead of point are related to localization. If remote sends numbers like 2300,55, this means it sends numbers in localized form. Generally, this is treated as Extremely Bad in network interaction: all data shall be sent between programs in locale-neutral form. Localized forms shall be used only in interaction with humans. So, the suggested way is to fix the remote side that it sent only neutral representations.

    But, if you have no influence onto remote side and have to deal with broken forms, try Java Scanner class methods with setting an expected locale or LocalDecimalSeparator separately. For a decimal comma, this is likely some European locale.

    (I cannot answer for DB issue.)