jQuery, change separator to dot and divide two selected numbers

跟風遠走 提交于 2021-02-17 07:20:13

问题


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.


回答1:


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.




回答2:


Try the following snippet:

var result = parseFloat($('.lot2').text()) / parseFloat($('span.Price').text());
$('.result').text(result.toString().replace('.', ','));

A fiddle can be found here: http://jsfiddle.net/moon9nve/

And more information on the replace function here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace



来源:https://stackoverflow.com/questions/30995666/jquery-change-separator-to-dot-and-divide-two-selected-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!