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.
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...
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?
There are several ways you could do this. @Laaouatni's answer is one example (and if you go with that one, make sure to mark that as the answer).
I'll give two others here.
Using string.prototype.slice
:
const intermediate = value.toFixed(2);
const result = intermediate.endsWith(".00") ? intermediate.slice(0, -1) : intermediate;
Using string.prototype.replace
:
const result = value.toFixed(2).replace(".00", ".0");
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.