gpt4 book ai didi

javascript - 在我的代码中用逗号分隔数字

转载 作者:行者123 更新时间:2023-11-28 18:18:03 25 4
gpt4 key购买 nike

我有以下代码。在文本输入字段中,如何才能将逗号适本地添加到数字中?例如,不要说“1000”,而是说“1,000”。或者再举个例子,如果我输入“1000000”,它会显示“1,000,000”。不幸的是JS不是我的强项。预先感谢您!

  function priceCalculation(a){
if(a <= 10000){
return 0.00099;
}else if(a >= 10001 && a <= 25000 ){
return 0.00095;
}else if(a >= 25001 && a <= 50000 ){
return 0.00089;
}else if(a >= 50001 && a <= 100000 ){
return 0.00075;
}else{
return 0.00075;
}
}

$('#likecount').keyup(function(){
var price = priceCalculation($(this).val());
console.log(price)
var total = $(this).val() * price;
$('#output').text(total.toFixed(2));
});



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="likecount" />
<p style="padding: 20px 0px; font-weight: bold; color: #222; ">Your Cost: <b><span> $</span><span id="output" style="color: #004f04;"></span></b></p>

我需要逗号的屏幕截图: enter image description here

最佳答案

使用 ECMAScript 6 的数字格式 ( see here ),您可以这样做:

更新脚本<​​/strong>:

function priceCalculation(a){
if(a <= 10000){
return 0.00099;
}else if(a >= 10001 && a <= 25000 ){
return 0.00095;
}else if(a >= 25001 && a <= 50000 ){
return 0.00089;
}else if(a >= 50001 && a <= 100000 ){
return 0.00075;
}else{
return 0.00075;
}
}

// number format set to en-US e.g (from 1500 to 1,500)
var numFormat = new Intl.NumberFormat("en-US");

$('#likecount').keyup(function(e){
// if a '.' is pressed
if($(this).val().endsWith('.')) {
return;
}

// if input value is empty then assign '0' else the original value
var inputVal = $(this).val() === ''?'0':$(this).val();

// replace the ',' to '' so we won't get a NaN result
// on arithmetic operations
inputVal = parseFloat(inputVal.replace(/[$|,]/g, ''));
var price = priceCalculation(parseInt(inputVal));
var total = inputVal * price;
var formatted = numFormat.format(inputVal) // set format to input
$(this).val(formatted); // display the formatted input back
$('#output').text(numFormat.format(total)); // display the total price
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="likecount" />
<p style="padding: 20px 0px; font-weight: bold; color: #222; ">Your Cost: <b><span> $</span><span id="output" style="color: #004f04;"></span></b></p>

关于javascript - 在我的代码中用逗号分隔数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40500131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com