Search code examples
javascriptjqueryreplaceseparatordivide

jQuery, change separator to dot and divide two selected numbers


var result = parseFloat($('.lot2').text()) / parseFloat($('span.Price').text());
$('.result').text(result);
});

How can I convert selected values from comma separated values to dot separated values? There is this function str.replace, but I don't know how to put it in the function.


Solution

  • How can I convert selected values from comma separated values to dot separated values?

    From that, I take it that the values you get from $('.lot2').text() and $('span.Price').text() will use , as the decimal point rather than . (as is the case in some locales). I assume that you may also have . as a thousands separator in there.

    If that's what you mean, then you need to do the , => . conversion, remove the . thousands separator, then parse the result, then do . => , conversion on the resulting value (and possibly add the . thousands separator). Here it is with each step separate for clarity:

    // Get lot 2
    var lot2 = $('.lot2').text();
    // Remove all `.` thousands separators, replace the one `,` decimal separator with `.`
    lot2 = lot2.replace(/\./g, '').replace(",", ".");
    // Same with price
    var price = $('span.Price').text().replace(/\./g, '').replace(",", ".");
    // Parse them and get the result
    var result = parseFloat(lot2) / parseFloat(price);
    // Replace the `.` decimal separator with `,`
    result = String(result).replace(".", ",");
    // Show result
    $('.result').text(result);
    

    If you want to add . thousands separators in there, this question and its answers (and several others here on SO) show how to do that, just use . rather than ,.

    Since this is likely to come up repeatedly in your code, you probably want to put both functions (locale form => JavaScript form, JavaScript form => locale form) into functions you can reuse.