18

Give me a native (no jQuery, Prototype, etc. please) JavaScript function that converts numbers as follows:

input:  0.39, 2.5,  4.25, 5.5,  6.75, 7.75, 8.5
output: 0.39, 2.50, 4.25, 5.50, 6.75, 7.75, 8.50

E.g., in Ruby, I'd do something like this:

>> sprintf("%.2f", 2.5)
=> "2.50"

The output may be a number or a string. I don't really care because I'm just using it to set innerHTML.

Thank you.

ma11hew28
  • 121,420
  • 116
  • 450
  • 651
  • 1
    @T.J.Crowder, sorry for not responding to your comment. Thank you for pointing that out and for asking me to clarify. I don't remember what I wanted, but let's just say `5.52` because that's what [`Number.prototype.toFixed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) seems to return, and I accepted that as the answer. – ma11hew28 Apr 28 '20 at 17:33
  • 1
    @T.J.Crowder, . If only Stack Overflow had a badge for that. (It's all good.) Thanks! You too, happy coding! :-) – ma11hew28 Apr 28 '20 at 17:59
  • Possible duplicate of [Format number to always show 2 decimal places](https://stackoverflow.com/q/6134039/242933) – ma11hew28 Apr 28 '20 at 18:09

4 Answers4

32
input = 0.3;
output = input.toFixed(2);
//output: 0.30
Eric Fortis
  • 16,372
  • 6
  • 41
  • 62
9

You can use the toFixed() method on Number objects:

var array = [0.39, 2.5,  4.25, 5.5,  6.75, 7.75, 8.5], new_array = [];
for(var i = 0, j = array.length; i < j; i++) {
    if(typeof array[i] !== 'number') continue;
    new_array.push(array[i].toFixed(2));
}
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
4

Use toFixed with 2 as the number of decimal places.

Jacob
  • 77,566
  • 24
  • 149
  • 228
1

Alternatively you can use Intl.NumberFormat() with { style: 'percent'}

var num = 25;

var option = {
  style: 'percent'

};
var formatter = new Intl.NumberFormat("en-US", option);
var percentFormat = formatter.format(num / 100);
console.log(percentFormat);
StangSpree
  • 421
  • 1
  • 5
  • 22
  • Nice. Thanks. Except your code doesn't work exactly for the inputs & outputs in the body of my question. I just edited the title of my question to better match its body. This way answers my question: `console.log(new Intl.NumberFormat('en-US', {minimumFractionDigits: 2}).format(2.5))`. – ma11hew28 Apr 28 '20 at 18:14