Как прибавить проценты к цене в javascript
Перейти к содержимому

Как прибавить проценты к цене в javascript

  • автор:

как прибавить проценты к цене в javascript

Аватар пользователя Aleksey

Для прибавления процентов к цене в JavaScript можно использовать следующую формулу:

В этом примере мы создали переменную price , которая содержит цену, и переменную percent , которая содержит процент, который мы хотим добавить к цене. Затем мы использовали формулу price + (price * percent / 100) для вычисления новой цены с учетом процента. Результат мы записали в переменную newPrice и вывели ее в консоль.

Вы можете изменять значения переменных price и percent , чтобы получить разные результаты.

Добавить проценты к числам

Как я могу добавить проценты к сумме? Я пытался var sum = 3.25 + ‘3.4%’; , но это не сработало. Я просто получаю 0.00 в качестве ответа.

2 ответа

«Добавить процент к числу» означает «умножить число на (1 + pct) »:

Вы можете эквивалентно пропустить 1 (я так об этом думаю) и добавить:

Поэтому, если вы начинаете со строкового представления в процентах, вы можете использовать parseFloat() , чтобы сделать его числом:

Функция parseFloat() удобно игнорирует завершающие нечисловые символы, такие как знак «%». Обычно это своего рода проблема, но в этом случае это экономит шаг дезинфекции строки.

Конкатенация строк и добавление чисел с использованием одного и того же символа +. Вы должны использовать () вокруг чисел.

Add percent to numbers

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.

4 Answers 4

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

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

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

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.

JavaScript — Calculating a number's percentage value tutorial

The JavaScript Math object doesn’t have any built-in method to calculate the percentage of a number, so if you want to find out the percentage of a specific number, you need to create your own custom function.

For example, the code below will find what 20% of 250 is using the calcPercent() function:

To write the calcPercent() code, we need to first understand the formula to calculate the percentage number.

To find 20% of 250, you need to divide 20 by 100 and then multiply it by 250 :

Now that you know the formula for calculating percentages, you can extract the code as a helper function:

Now you can call the helper function calcPercent() anytime you need to calculate a number’s percentage value:

Rounding the result to 2 decimals

Sometimes, a percentage calculation may return a floating number as follows:

If you need to round the number to 2 decimals, then you can use a combination of toFixed() and parseFloat() methods to return the number in 2-decimal format.

Here’s the full function code:

Instead of returning 0.666 , the function will return 0.67 because it rounds the decimal numbers to a maximum length of two.

Get 100 JavaScript Snippets Book for FREE ��

100 JavaScript snippets that you can use in various scenarios

Save 1000+ hours of research and 10x your productivity

About

Sebhastian is a site that makes learning programming easy with its step-by-step, beginner-friendly tutorials.
Learn JavaScript and other programming languages with clear examples.

Free Code Snippets Book

Get my FREE code snippets Book to 10x your productivity here

Ezoic

report this ad

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *