CMS Development

FSandbox
Participant

String to Float conversion

Hi,

 

I am facing problem in string to float conversion in dutch language.

I need to get values from URL and convert to float because further calculation.

 

/nl-be/kantoren?lat=50.864860&lon=2.887811&location=8900

IN URL Lat = (String: 50.864860)
IN URL Lon = (String: 2.887811)

AFTER FLOAT Lat = (Float: 5.086486E7)
AFTER FLOAT Lon = (Float: 2887811.0)

 

After conversion values are not correct.

But in english language its working fine.

 

/en/kantoren?lat=50.864860&lon=2.887811&location=8900
IN URL Lat = (String: 50.864860)
IN URL Lon = (String: 2.887811)

AFTER FLOAT Lat = (Float: 50.86486)
AFTER FLOAT Lon = (Float: 2.887811)

I am using |float filter for coversion and get value from URL using request.query_dict.

 

Thanks.

 

 

 

0 Upvotes
2 Replies 2
Jaycee_Lewis
Community Manager
Community Manager

String to Float conversion

Hey @FSandbox 👋 How about something like this? My function assumes you're only dealing with US or Dutch locales. 

function safeFloatParse(value, locale = 'en-US') {
    // Validate locale
    if (!['en-US', 'nl-BE'].includes(locale)) {
        throw new Error(`Unsupported locale: ${locale}`);
    }

    if (typeof value !== 'string') {
        value = String(value);
    }

    // Define separators
    const separators = {
        'nl-BE': { thousand: '.', decimal: ',' },
        'en-US': { thousand: ',', decimal: '.' }
    };

    const { thousand, decimal } = separators[locale];

    // Remove separators and normalize
    const normalizedValue = value
        .trim() // Handle whitespace
        .replace(new RegExp(`\\${thousand}`, 'g'), '')
        .replace(decimal, '.');

    // Parse
    const parsedValue = parseFloat(normalizedValue);

    // Validate
    if (isNaN(parsedValue)) {
        throw new Error(`Unable to parse value: ${value}`);
    }

    return parsedValue;
}

I tried to:

  • use explicit locale validation
  • trim whitespace
  • use an Object for readability
  • include error handling

I hope this helps get you moving forward! — Jaycee

 

linkedin

Jaycee Lewis

Developer Community Manager

Community | HubSpot

0 Upvotes
WesQ
Contributor

String to Float conversion

Hello! @FSandbox 

 

Why It's Happening:

  • In English, 50.864860 is treated as 50 point 864860.
  • In Dutch, 50.864860 is interpreted differently (it might not parse correctly because . could be considered a thousands separator, leading to 50.864860 being read as 50864860).

 

Possible Solution:

  1. Set locale to English temporarily
  2. Get values
  3. Set locale back to Dutch

 

WesQ_0-1737853949136.pngWas I able to help answer your question? Help the community by marking it as a solution.

0 Upvotes