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
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
2means, 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?