我正在尝试使用JavaScript来移动逗号的位置。我已设法删除我需要删除的字符串的所有部分。唯一的问题是逗号处于错误的位置。
目前的结果是425.00
,但我只想要'42 .50'
success: function(result) {
if (result != '') {
alert(" "+result+" ");
}
var discountVal = result.replace(/\D/g,'');
newDiscountVal = discountVal.replace(7.50, '');
$("input#amount").val(discountVal);
}
我使用字符串和echo - 数字组合来抓取数据库回显值..
答案 0 :(得分:0)
如果是数字,你可以除以10
如果是字符串,你可以这样做:
var ind = text.indexOf('.');
text = text.replace('.', '');
text.slice(0, ind-1) + '.' + text.slice(ind-1, text.length)
答案 1 :(得分:0)
您可以除以10,然后使用toFixed(2)转换回String,强制格式化2位小数
Javascript允许将字符串隐式转换为数字,首先将字符串转换为数字,因此将字符串除以数字是有效的。
>>> 1.12345678901234567890
1.1234567890123457
>>> 0.0001100110011001100110011001100110011001100110011
0.00011001100110011001
请注意,由于四舍五入,此方法具有不同的行为。考虑案例9.99。如果你使用字符串操作技术,你将得到" .99",用上面的除以10的方法得到" 1.00"。然而,从评论中所说的,我相信你的输入总是以.00而不是其他任何东西结束,所以现实中没有任何区别。
答案 2 :(得分:-1)
这就是我解决它的方法..
var discountVal = result.replace(/\D/g, '');
var newDiscountVal = discountVal.replace(7.50, '');
var lastDigits = newDiscountVal.substr(newDiscountVal.length - 2);
var removedDigits = newDiscountVal.slice(0,newDiscountVal.length - 2);
var discountRealValue = removedDigits + '.' + lastDigits;
$("input#amount").val(discountRealValue);
干杯