[英]javascript toFixed(2) not working in calculations
我有一些代碼涉及我試圖只顯示兩位小數的計算。 我正在使用.toFixed(2),但它仍然無法正常工作。 我把它放在正確的位置了嗎?
function SetFoodItems(amount) {
// returns the amount in the .99 format
return amount == Math.floor(amount)) ? amount + '.00' : ((amount * 10
== Math.floor(amount * 10)) ? amount + '0';
}
function SelectFoodItems(form) {
var UpdateCosts = (form.quantity.value - 0) * (form.unitcost.value -
0) + (form.quantity1.value - 0) * (form.unitcost1.value - 0) +
(form.quantity2.value - 0) * (form.unitcost2.value - 0) +
(form.quantity3.value - 0) * (form.unitcost3.value - 0).toFixed(2);
UpdateCosts = Math.floor(subtotal * 1000) / 1000;
form.subtotal.value = '$' + SetFoodItems(subtotal).toFixed(2);
var tax = (UpdateCosts / 100 * (form.rate.value - 0).toFixed(2);
tax = Math.floor(tax * 1000) / 1000;
form.tax.value = '$' + SetFoodItems(tax);
total = UpdateCosts + tax;
total = Math.floor((total * 1000) / 1000);
form.total.value = '$' + SetFoodItems(total).toFixed(2;
如上所述,您的.toFixed()
方法返回一個字符串; 原因是類型轉換。 例如,字符串1 + "0"
的加法會將 1 轉換為字符串,因此您會得到10
作為字符串。 如果您在線搜索,您可以找到有關它的更多信息。
現在你知道了; 要解決您的問題,您可以使用不同的選項。 取決於您希望代碼返回的內容,取決於您最喜歡哪一個:
parseInt('your-number-string').toFixed(2)
parseFloat('your-number-string').toFixed(2)
Number('your-number-string').toFixed(2)
這些中的任何一個都會給你一個數字。
這有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.