Search code examples
javascriptleafletgeojson

Add commas to a number in a popup in Leaflet JavaScript


I've created a popup that has a number in it. The data is being imported from a geoJSON file. Is there a way to include a comma separator? I've tried ".toLocaleString()" and ".toString()". Assistance with my syntax would be appreciated, thank you.

layers.one = L.geoJson(data, {
            filter: function (feature, layer) {
                return (feature.properties.list_price <= 250000);
            },
            // Creates popup
            onEachFeature: function (feature, layer) {
                // console.log(layer)  // To test for function operation
                layer.bindPopup(
                    '<h3>' +
                    feature.properties.full_address +
                    '</h3><hr><p>' +
                    '$' +
                    feature.properties.list_price.toLocaleString().replace(/B(?=(d{3})+(?!d))/g, ",")
                ) + '</p>'
            }
        })

enter image description here


Solution

  • Use the Intl.NumberFormat constructor to build a formatter that has certain requirements. Like the type of currency you're trying to use. This is actually the working part of Number.prototype.toLocaleString().

    This also doesn't require you to prefix your string with a $ sign as the formatter will take care of the way the currency is represented.

    const value = 289900;
    
    const formatter = new Intl.NumberFormat('en-US', {
      style: 'currency', 
      currency: 'USD',
    });
    
    const formattedValue = formatter.format(value);
    console.log(formattedValue);