Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do I retain the the zero at the end when I divide a number like 12330 by 100 in Javascript

how do I divide 12330 by 100 to give me 123.30

trying 12330/100 in JS gives 123.3 but I want the 0 at the end to stay

also, I need the function to not give .00

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

so 100/100 should give 1 and not 1.00

tried using .toFixed(2). but it only solved the first case and not the second.

>Solution :

use toFixed https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

console.log(
  (12330 / 100).toFixed(2)
);

here 2 means, the precision of float


Attention: also when the number isn’t a float it will do number.00 (in the most of cases this is good behavior)

but if isn’t good for you, see the next edited answer…


new edited answer

if the .00 gives you problems, use this:

% operator, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder

function convert(value) {
  if (value % 1 === 0) {
    return value;
  }

  return value.toFixed(2);
}

// tests


console.log(convert(12330 / 100)); // should return value with toFixed

console.log(convert(100 / 100)); // should return 1 (no toFixed)

console.log(convert(100 / 10)); // should return 10 (no toFixed)

for understanding more about the solution you can see this StackOverflow question on this topic How do I check that a number is float or integer?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading