为什么 6.00 +(加)5.00 = “5.006.00"? [英] Why does 6.00 + (plus) 5.00 = "5.006.00"?

查看:61
本文介绍了为什么 6.00 +(加)5.00 = “5.006.00"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个变量从 PHP echo...

If I have a variable that is given a "numeric" value from a PHP echo...

var names_each = <?php echo $ind_name_each; ?>;

...和 ​​$ind_name_each 派生自 decimal(5,2) 类型的 MySQL 列,它是 JavaScript 中的数字还是字符串?

...and $ind_name_each is derived from a MySQL column of type decimal(5,2), is it a number or a string in JavaScript?

如果 all_total = 6.00和 names_each = 5.00我这样做:

if all_total = 6.00 and names_each = 5.00 and I do this:

all_total = parseInt(names_each) + all_total;

我得到 56.00

all_total = names_each + all_total;

我得到 5.006.00

I get 5.006.00

all_total = parseFloat(names_each) + all_total;

我得到 56.00

我需要了解一下.

推荐答案

两个变量都是字符串:

var names_each = '5.0', all_total = '6.0';

所以 + 操作连接这些字符串:

so the + operation concatenates those strings:

console.log(names_each + all_total);  // '5.0' + '6.0' => '5.06.0'
console.log(parseInt(names_each) + all_total); // 5 + '6.0' => '5' + '6.0' => '56.0'

但是如果您先将它们解析为数字,那么您可以使用 + 来添加它们:

but if you parse them to numbers first, then you can use + to add them:

all_total = parseInt(names_each) + parseInt(all_total);
console.log(all_total);  // 5 + 6 => 11

这篇关于为什么 6.00 +(加)5.00 = “5.006.00"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆