0

I'm trying to format a string to show two sig figs after the decimal. I want to do this without using built-in methods like 'Math' and such. I have something where I can do that, but the issue comes when the number is just '4.5' for example, I need to add a 0 onto it, but I'm having trouble. Here's my code so far.

function toFixed(num){
let elem = "";
// let x = "";
for (let i = 0; i < num.length; i++) {

  if(num[i - 2]  === '.'){  // num[i] happens to be the third 8

  break;
  }
  // elem += num[i];
elem += num[i];
elem += "0";

} 
return elem
}

console.log(toFixed("7.88888888")) // "7.88"
console.log(toFixed("77645345.987654")) //77645345.88
console.log(toFixed("1")) // "1.00"
console.log(toFixed("4.5")) // "4.50"

Right now I'm getting 0's after each number it seems.

hbrashid
  • 21
  • 5
  • Does this answer your question? [Formatting a number with exactly two decimals in JavaScript](https://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript) – Cully Apr 17 '20 at 05:58
  • for example var num = 5.5, var n = num.toFixed(2)? Javascript number has toFixed function for you to format your number – lhoro Apr 17 '20 at 05:59
  • Yes, but I'm trying to do it without methods. – hbrashid Apr 17 '20 at 06:01
  • Why are you trying to do it without using built-ins? Just to learn or do you have a restriction of some kind? – Cully Apr 17 '20 at 06:03
  • @Cully, yes to learn. – hbrashid Apr 17 '20 at 06:03
  • BTW, if you want to implement your own method, for 7.8888, it should be 7.89 instead of 7.88, your function doesn't round up or round down properly – lhoro Apr 17 '20 at 06:14
  • Right now I'm trying to make 4.5 -> 4.50 without using methods. – hbrashid Apr 17 '20 at 06:18

2 Answers2

1

Without Math:

function toFixed(num) {
  let [a, b = ""] = num.split(".");
  
  b += "00";
  
  return `${a}.${b.slice(0, 2)}`;
}

console.log(toFixed("7.88888888")) // "7.88"
console.log(toFixed("77645345.987654")) // "77645345.98"
console.log(toFixed("1")) // "1.00"
console.log(toFixed("4.5")) // "4.50"

Without any builtin methods:

function toFixed(num) {
  const len = num.length;
  let result = "";    

  for (let i = 0; i < len; i++) {
    const c = num[i];
    
    if (c === ".") {
      return `${result}.${num[i + 1] || 0}${num[i + 2] || 0}`;
    }
    
    result += c;
  }
  
  return `${result}.00`;
}

console.log(toFixed("7.88888888")) // "7.88"
console.log(toFixed("77645345.987654")) // "77645345.98"
console.log(toFixed("1")) // "1.00"
console.log(toFixed("4.5")) // "4.50"
Yonggoo Noh
  • 1,811
  • 3
  • 22
  • 37
0
function toFixedNumber(num) {
    let elem = +num;
    return elem.toFixed(2)
}

console.log(toFixedNumber("7.88888888")) // "7.88"
console.log(toFixedNumber("77645345.987654")) //77645345.88
console.log(toFixedNumber("1")) // "1.00"
console.log(toFixedNumber("4.5")) // "4.50"

For your reference

Rajan
  • 1,512
  • 2
  • 14
  • 18