简体   繁体   中英

Javascript parseInt parseFloat and rounding decimals

I have a javascript to autofill some inputs, without rounding it with my code it works fine it changes and autofill the inputs, but trying to add Math.round or round it rounds the decimals but does not change does not autofill if some addEventListener changes like it must do

Working code

taxes.value = parseInt(parseFloat(totaltopay.value) * (1.00/1.19));

Adding some code to round the decimals it does not autofill the inputs

taxes.value = parseInt(parseFloat(Math.round(totaltopay.value) * (1.00/1.19)));

Any way to round this result and make it work?

It must do the follow:

taxes = 23123.764345645 round and show only to 23124 without dots without commas

EDIT

The input quantity changes the total to pay with input quantity * input sale price and that gives a total price to pay, this totaltopay input we take the amount an get the taxes, it works without rounding, but trying to round it the addEventListener stop working... As you may understand the taxes are autofilles too when changing sale price or quantity because the totaltopay change and so the taxes

So, things to keep in mind:

  • parseInt() creates integers. You give it a string or a number and you get a number without decimal cases. Note: parseInt has a radix, you probably want to use the radix 10: parseInt(yourString, 10);
  • parseFloat() takes a string and returns a number, with decimal cases
  • Math.round() takes a number (*) and returns a integer, rounded to the nearest integer
  • Number() takes a string (or number) and converts it into a number, keeping decimal cases

So, what you need is:

taxes.value = Math.round(Number(totaltopay.value) * 1.00 / 1.19);

(*) - Math.round works with strings, but MDN's docs say: give it a number

You just need to use Math.round() which rounds the number and returns an integer value. While applying * (multiplication) or / (division) the values are automatically getting parsed to Number so there is no need of hard coded methods to parse them.

taxes.value = Math.round(totaltopay.value * 1.00 / 1.19);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM