2015-04-25 26 views
-1

我有一個文本框,用戶輸入的數字大部分都是浮點數據類型。該值然後被添加到某個先前的值。 當用戶添加像0.123這樣的浮點數時,它會很好地添加,但是當他像.123一樣添加它時,它會拋出錯誤Nan。 我正在使用以下代碼。如何操作在javascript/jquery中從.somevalue開始到0.somevalue的浮點值?

var labor_cost = Number($("#labor_cost").val()); 
      var other_cost = Number($("#other_cost").val()); 
      var profitValue = Number($("#profitValue").val()); 
      var ingCost = Number($("#productTotalcost").val()); 
      profitAmount = ((ingCost+other_cost+labor_cost)*profitValue/100);     
      $("#showproposedprice").html((ingCost+other_cost+labor_cost+Number(profitAmount)).toFixed(2));              
      $("#proposedprice").val((ingCost+other_cost+labor_cost+Number(profitAmount)).toFixed(4)); 

請幫助我,我怎麼可以跳過或操縱浮點數.1230.123? 謝謝。

+1

請出示你的代碼。這通常不會發生。 '.123'是一個非常好的浮點值。 – Barmar

+1

'parseFloat(「.123」)'返回0.123'。 – Barmar

+0

與「+」,「123」一樣,或者將字符串強制轉換爲數字的任何其他操作。 –

回答

-1

更新:我試過了你的代碼,並且不能重現錯誤。這是我所做的(包括HTML),並帶有更新的小提琴。你能在小提琴中重現錯誤嗎?如果是這樣,那麼讓我知道你在每個文本框中的內容。如果沒有,你的代碼比較,這一點,看看有什麼不同:

<p>Labour cost: <input type="text" id="labor_cost" /></p> 
<p>Other cost: <input type="text" id="other_cost" /></p> 
<p>Profit Value: <input type="text" id="profitValue" /></p> 
<p>Product Total Cost: <input type="text" id="productTotalcost" /></p> 
<button id="submit">click</button> 

<hr/> 
<p>Show Proposed Price: <span id="showproposedprice"></span></p> 
<p>Proposed Price: <input type="text" id="proposedprice" /></p> 

<script type="text/javascript"> 
    $("#submit").click(function() { 
    var labor_cost = Number($("#labor_cost").val()); 
    var other_cost = Number($("#other_cost").val()); 
    var profitValue = Number($("#profitValue").val()); 
    var ingCost = Number($("#productTotalcost").val()); 
    var profitAmount = ((ingCost+other_cost+labor_cost)*profitValue/100); 
    $("#showproposedprice").html((ingCost+other_cost+labor_cost+Number(profitAmount)).toFixed(2));              
    $("#proposedprice").val((ingCost+other_cost+labor_cost+Number(profitAmount)).toFixed(4)); 
    }) 
</script> 

http://jsfiddle.net/r8xburf6/2/

相關問題