gpt4 book ai didi

javascript - jQuery/Javascript 拆分字符串计算

转载 作者:行者123 更新时间:2023-11-30 10:43:13 26 4
gpt4 key购买 nike

我正在创建一个产品页面,要求在数量值更改时更新价格。使用了两个表单字段:.orig_price#quantity。这些值显然相乘。

我正在尝试拆分相乘的值,以便打印正确的格式(27.7043454575 应该是 27.70)。

我的代码:

jQuery("#quantity").change(function() {

jQuery("#pricediv").hide();

// store form values
var origprice = jQuery(".orig_price").val().substr(1);
var qty = jQuery("#quantity").val();

// calculate price
var sumValue = origprice * qty;

// split price
var splitprice = sumValue.split(".");
var pricepound = splitprice[0];
var pricepenny = splitprice[1].substring(0,2);

// update price

jQuery("#pricediv").html('£' + pricepound + '.' + pricepenny);
jQuery("#pricediv").fadeIn(1500);
});

如果我删除拆分并使用 sumValue 一切正常(但格式错误)。拆分不适用于计算吗?

最佳答案

您需要使用 sumValue.toFixed(2)

var sumValue = 27.7043454575;
sumValue.toFixed(2) // 27.70

.split 在数字类型上不存在。您将不得不使用 sumValue.toString().split('.'),无论哪种方式,这都比简单地坚持 .toFixed

关于javascript - jQuery/Javascript 拆分字符串计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9891210/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com