将百分比加到数字上 [英] Add percent to numbers

查看:103
本文介绍了将百分比加到数字上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将百分比加到总和上?我试过var sum = 3.25 + '3.4%';,但是没有用.我只是得到0.00作为答案.

How can I add percent to a sum? I have tried var sum = 3.25 + '3.4%'; but it didn't work. I'm just getting 0.00 as an answer.

推荐答案

将百分比添加到数字中"表示将数字乘以(1 + pct)":

To "add a percent to a number" means "multiply the number by (1 + pct)":

var sum = 3.25;
sum = sum * (1 + 0.034);

您可以等效地跳过1(这就是我的想法)并添加:

You could equivalently skip the 1 (that's just the way I think about it) and add:

var sum = 3.25;
sum += sum * 0.034;

因此,如果您以百分比的字符串表示形式开始,则可以使用parseFloat()将其设置为数字:

So if you're starting off with a string representation of a percentage, you can use parseFloat() to make it a number:

var pct = "3.4%"; // or from an <input> field or whatever

pct = parseFloat(pct) / 100;

parseFloat()函数可以方便地忽略尾随的非数字内容,例如%"符号.通常这是一个问题,但是在这种情况下,它省去了对字符串进行清理的步骤.

The parseFloat() function conveniently ignores trailing non-numeric stuff like the "%" sign. Usually that's kind-of a problem, but in this case it saves the step of sanitizing the string.

这篇关于将百分比加到数字上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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