首页 > 解决方案 > var 值转换为 2 个小数位值

问题描述

我正在尝试创建一些简单的代码来计算已通过复选框形式选中的产品的价值。这些值都是十进制 (0.00) 形式。Javascript 部分仅显示整体。谁能协助如何做到这一点?

这是代码

<input type="checkbox" class="css-checkbox" name="iMac" id="<?php echo $rows2['id']; ?><?php echo $rows2['product_name']; ?>" value="<?php echo $rows2['product_price']; ?>"></input>

    function computer() {

    var userMesssage = document.getElementById("userMesssage");

    var iMac = document.orderForm.iMac; // array of inputs
    var totalOrder = "";                // list all checked ids
    var totalCost = 0;                  // add values to calculate cost

    for (var i = 0; i < iMac.length; i++){
        if (iMac[i].checked) {
            totalOrder += iMac[i].id + " ,<br />";       // add ids separated by spaces
            totalCost += parseInt(iMac[i].value); // add value attributes, assuming they are integers
        }
    }

    // show total order and cost
    userMesssage.innerHTML = "<b>Your Budget</b>: <br />" + totalOrder + "<br />Total Budget: $" + totalCost;
    userMesssage.style.color = "#fff";
    }

标签: javascript

解决方案


您必须使用 .toFixed() 函数将十进制转换为整数。

totalCost += (+(iMac[i].value).toFixed());

+前面添加了一个附加项,用于将字符串转换为数字。

console.log(+(Math.random()*10).toFixed());


推荐阅读