A
A
Alexander Belov2017-02-08 11:36:36
JavaScript
Alexander Belov, 2017-02-08 11:36:36

How to work with the calculation of the amount of goods in Javascript?

The situation is as follows: there are goods, you need to work with their cost (addition, subtraction, multiplication).
The price of goods is indicated in the format "Rubles.kopecks"
I googled that, it seems, initially you need to hammer in the price in kopecks, and then f*** everything *100 and the result is /100 or something like that.
Is there a human approach to the solution?
If my price is specified as a string, then it is parsed into a number (for the correct calculation), and then the answer is displayed again as a string (to be displayed in a format with a space like "20 070.80"), what should I do?
A primitive example of what kind of game it can result in.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Luzanov, 2017-02-08
@AlexanderBelov

Your mistake is that you first concatenate strings and then do parseInt(). As a result, the columbus turns out.
What is supernatural in this? JS has problems with fractional precision. You will have to do this anyway.

let one = parseFloat("10.77") * 100,
    two = parseFloat("5.89") * 100,
    three = parseFloat("20.04") * 100,
    view = document.getElementById("container");

let sum = (one + two + three) / 100;
console.log(sum)

view.innerHTML = sum.toFixed(2);

Is someone forbidding you to use parseFloat()?
Bonus
Bonus number 2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question