Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

javascript - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...