Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplication int and float(double) in JavaScript [duplicate]

Tags:

javascript

I want to make multiplication using JavaScript.

Multiplication of 2 and 0.15 is 0.3 but 3 and 0.15 is 0.44999999999999996. I want to get 0.45 such as result. How can I do it with JavaScript?

like image 546
Afsun Khammadli Avatar asked May 17 '13 11:05

Afsun Khammadli


People also ask

Can you multiply float by int JavaScript?

There is no int or float in JavaScript. Everything is a double . That being said, you're looking for toFixed() if you want to convert your value into a string.

Can we multiply float and double?

if you multiply double with float variable the result will be double and you won't loose accuracy. However it depends on where the result is saved, if it's saved into a float variable then accuracy is lost.

Can you multiply an int and a double?

This is not possible.

Can you multiply a float and an int?

The result of the multiplication of a float and an int is a float . Besides that, it will get promoted to double when passing to printf . You need a %a , %e , %f or %g format. The %d format is used to print int types.


1 Answers

It's a rounding error. You may want to round your number to a fixed amount of digits, like this:

parseFloat((your_number).toFixed(2));
like image 116
Simon M Avatar answered Oct 02 '22 05:10

Simon M