javascript - 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";
}
解决方案
您必须使用 .toFixed() 函数将十进制转换为整数。
totalCost += (+(iMac[i].value).toFixed());
+
前面添加了一个附加项,用于将字符串转换为数字。
console.log(+(Math.random()*10).toFixed());
推荐阅读
- server - 远程活动目录
- php - 在 Woocommerce 存档页面上将产品标题移到产品图片上方
- url - 如何在 Prestashop 的 TPL 格式中添加 hreflang
- c# - 使用 C# 读取/写入包含可变大小二维数组的结构体
- java - 平均计算器“从浮点数到整数的可能有损转换” - Java 赋值
- php - 自动完成搜索输入(无法加载 https://proj.test/autocomplete-search?term=tes: No 'Access-Control-Allow-Origin)
- javascript - 允许嵌套在相对位置 div 中的绝对位置 html div 具有可滚动的溢出-y 内容和可见的溢出-x 内容
- ruby-on-rails - RAILS Prism gem 仅在直接 URL 或刷新页面时突出显示代码示例
- javascript - React ES6 App - 本地 API 调用
- ios - 谷歌视觉图像标签 API 错误