2

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.

Thanoss
  • 439
  • 5
  • 11
  • 3
    as a number, `123.30` is simply the same as `123.3` and JS will always display the simpler version. You want the *string* `"123.30"`, in which case use the `toFixed` method. – Robin Zigmond Sep 08 '22 at 20:06

2 Answers2

4

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 this checking (value % 1 === 0) you can see this StackOverflow question on this topic How do I check that a number is float or integer?

Laaouatni Anas
  • 4,199
  • 2
  • 7
  • 26
  • Thanks, the issue is I don't want .00 using toFixed(2) on a perfect fraction like (100 / 100).toFixed(2) will give 1.00 – Thanoss Sep 08 '22 at 20:13
1

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");
Nathan
  • 505
  • 2
  • 8