2015-06-04 16 views
0

我目前正試圖在jquery中製作一個計算器,並且我設法做了幾個但是我列舉了一些問題,需要一些幫助。 我想放置一個數學。對我的代碼進行四捨五入的操作,使分割結果更加令人愉快,但不知道確切的位置。我嘗試過.toFixed,但我不喜歡那個例如,如果我有5/2的操作,結果將是2500,我希望它看起來像2.5。我是否正在處理錯誤的var?我搞不清楚了。下面是代碼:我想在jquery文件中使用math.round函數,但我不知道要把它放在哪裏才能得到想要的結果

$operators.click(function (event) { 
    event.preventDefault(); 
    var currValue = $(this).text(); 
    var currOperand = parseFloat($display.text()); 
    if (currValue != 'CE') { 
     if (operation != null && !afterOperation) { 
      switch (operation) { 
       case '+': 
        $display.text(operand + currOperand); 
        break; 
       case '-': 
        $display.text(operand - currOperand); 
        break; 
       case '*': 
        $display.text(operand * currOperand); 
        break; 
       case '/': 
        if (currOperand != 0) { 
         $display.text((operand/currOperand).toFixed(3)); 
        } else { 
         alert("ERROR"); 
         reset(); 
        } 
        break; 

高度讚賞幫助

+0

你試圖做的不是「四捨五入」,這實際上會改變你不想在計算器應用程序中執行的結果值。相反,您正在嘗試根據您的視覺願望來格式化輸出。你不能用舍入函數來做到這一點。如果您仔細查看相關行,可以使用當前的格式:'.toFixed(3)',其基本意思是:「在小數點後顯示4位數字」。你可能想改變它。 – arkascha

回答

0

division情況下添加Number

$display.text(Number((operand/currOperand).toFixed(3))); 

這將字符串先轉換到Number

另一種方式

您還可以使用parseFloat

parseFloat((5/2).toFixed(3)) 
+0

爲什麼有2個小數位?在上面的例子中舍入有什麼幫助? – arkascha

+0

這要看情況,我會說。它確實a)不符合要求的示例,並且b)更改OP迄今爲止沒有理由實施的代碼。 – arkascha

+0

@arkascha請檢查更新後的答案 – Tushar

0

您可以創建一個函數(getResult())比較師那的.toFixed()的結果,並返回最喜歡的合適的代表性所以:

function getResult(a, b) { 
 
    var c = a/b, //numeric 
 
     d = c.toFixed(3); //string 
 
    return c == d ? c : d; 
 
} 
 

 
$('pre > span[data-a]').each(function() { 
 
    $(this).next().text(getResult($(this).data('a'), $(this).data('b'))); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<pre> 
 
<span data-a="5" data-b="2">5/2 = </span><span></span> 
 
<span data-a="5" data-b="3">5/3 = </span><span></span> 
 
<span data-a="4" data-b="3">4/3 = </span><span></span> 
 
</pre>

+0

哇,你真的知道代碼。非常感謝你的回覆,但我認爲你的方法對我的水平來說是相當先進的。我剛剛開始3天前,我也想確保我明白我在做什麼。當我學到更多的東西時,我會回到你的答案,並嘗試你的版本,使我的代碼更有效和乾淨。 $ display.text(Number((操作數/ currOperand))。toFixed(3)));正如上面的用戶所提出的,現在似乎已經成功了。再次感謝 –

相關問題