在 JavaScript 中计算百分比
本文将介绍如何使用 JavaScript 计算任意数字的百分比。
在 JavaScript 中计算百分比
在 JavaScript 中获取任意数字的百分比非常容易。 要获得基础数学中任何数字的百分比,我们必须将所需的百分比乘以该数字。
在下面的 JavaScript 代码示例中,我们创建一个名为 calPercnt 的函数。 在该函数中,我们使用一个简单的公式来获得 500 的 20%。
在公式中,我们将 20 除以 100,等于 0.2。 然后我们将 0.2 乘以 500,得到 100,即 500 的 20%。
示例代码:
function calPercnt(num, percentage){
const result = num * (percentage / 100);
return parseFloat(result.toFixed(2));
}
const percntVal = calPercnt(500, 20);
console.log(percntVal);
输出:
100
这是 JavaScript 中计算数字百分比的一种方法。 我们还可以使用自定义 JavaScript 函数来计算数字的百分比。
使用自定义 JavaScript 函数计算百分比
它是 JavaScript 中用于计算任何数字的百分比的最简单且简短的方法之一。 这个自定义函数有两个参数:我们要计算的百分比和我们要获取百分比的数量。
我们在console.log中调用函数calcPercnt,在运行时,我们给出两个要计算百分比的参数。
在代码示例中,我们给出了 console.log (1000, 20)
,它将计算 1000 的 20%。
这些是函数用于计算百分比的几个示例 console.log(calcPercnt(1000, 30));
、console.log(calcPercnt(1000, 40));
、console.log(calcPercnt(1000, 45) );
, console.log(calcPercnt(1000, 50));
, console.log(calcPercnt(100, 10));
.
我们在自定义函数的 console.log 部分中给出参数。 我们得到了输出中要计算的数字的百分比。
示例代码:
function calcPercnt(percent, num){
return (percent / 100) * num;
}
console.log(calcPercnt(1000, 20));
console.log(calcPercnt(1000, 30));
console.log(calcPercnt(1000, 40));
console.log(calcPercnt(1000, 45));
console.log(calcPercnt(1000, 50));
console.log(calcPercnt(100, 10));
输出:
200
300
400
450
500
10
在上面的输出中,我们得到 200,即 1000 的 20%。然后我们得到 300,即 1000 的 30%,然后我们得到 400。
这个自定义函数通过将值赋予参数来帮助我们一次找到多个数字的百分比。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。