[英]javascript convert $ string to number
我有一組具有$ 1.00,$ 1654.31等值的表單字段,我只想將它們轉換為數字字符串,以便我可以計算這些值。
即時通訊遍歷每個,但登錄到控制台時一直保持NaN。
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val() ) );
});
每次返回NaN時,我想知道是否有一種簡單的方法可以將美元值字符串轉換為僅用於計算的數值?
提前致謝
嘗試
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val().replace('$','') ) );
});
var numberWithoutDollar = numberWithDollar.replace(/^\$/, '');
您必須刪除數字以外的所有內容.
, -
和+
。
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val().replace(/[^\d\.\+-]/g, "") ) );
});
例子:
parseFloat("-1.00".replace(/[^\d\.\+-]/g, ""))
// -1
parseFloat("+1654.31 ".replace(/[^\d\.\+-]/g, ""))
// 1654.31
剛剛跳過美元符號。
parseFloat($(this).val().substr(1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.