2015-04-17 44 views
0

任何人都可以幫我解決我遇到的這個問題嗎?我使用下面的代碼來獲得輸入域Javascript格式浮點數的小數位數

parseFloat($("#salaryFrom").val()); 

唯一的問題是,如果在salaryFrom字段中的值以0結尾是取得成果削減的價值。例如8.50值返回爲8.5,我需要返回8.50

+1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Global_Objects/Number/toFixed – sinisake

+1

這就是將字符串轉換爲數字時會發生的情況,如果您想要8.50則刪除前導和後續的零 – adeneo

+0

這意味着您需要將值保留爲字符串。 8.5或8.50只是同一個浮點數的字符串表示。 –

回答

5

作爲浮點數8.50和8.5是相同的。然而,當你將你的號碼轉換爲一個字符串時,你可以指定你希望用於函數toFixed()的小數位數,例如

var a = parseFloat($("#salaryFrom").val()); 
var b = a.toFixed(2); 

功能toFixed()需要你想你的數字格式的小數位的數量,在這種情況下,2

0

JavaScript有一個toFixed()函數來格式化浮點數。所以,請嘗試一下。

tmp = parseFloat($("#salaryFrom").val()); 
formatted_val = tmp.toFixed(2); 
alert(formatted_val); 
+1

那麼爲什麼要使用parseFloat獲取一個數字,只能使用toFixed將其轉換回字符串? – adeneo

+0

@adeneo因爲String.prototype.fixed()做了不同的事情 – Jonathan

+1

@Jonathan - 是的,但究竟是什麼? parseFloat(「8.50」)toFixed(2)===「8.50」;'< - 什麼點 – adeneo

0

使用.toFixed(2)在JavaScript。 (2) - 其可選小數點後的位數。缺省值是0(小數點後沒有數字)

var num = 8.5; 
console.log(num.toFixed(2)) 

示例:使用toFixed

var numObj = 12345.6789; 

numObj.toFixed();  // Returns '12346': note rounding, no fractional part 
numObj.toFixed(1);  // Returns '12345.7': note rounding 
numObj.toFixed(6);  // Returns '12345.678900': note added zeros 
(1.23e+20).toFixed(2); // Returns '123000000000000000000.00' 
(1.23e-10).toFixed(2); // Returns '0.00' 
2.34.toFixed(1);  // Returns '2.3' 
-2.34.toFixed(1);  // Returns -2.3 (due to operator precedence, negative number literals don't return a string...) 
(-2.34).toFixed(1);  // Returns '-2.3' (...unless you use parentheses)