skip to Main Content

I need to convert decimal to string in some specific format

1.0 to "+01:00"
-4.0 to "-04:00"

I have used .toString() but that is only converting to string as expected how to convert it into above format. Please suggest

2

Answers


  1. You can create a custom function to convert number to your desired format using padStart and toFixed.

    const format = num => {
      const sign = num > 0 ? '+' : '-';
      const [first, second] = num.toFixed(2).split('.');
      return `${sign}${first.replace('-','').padStart(2, '0')}:${second}`
    }
    console.log(format(1.0))  // "+01:00"
    console.log(format(-4.0)) // "-04:00"
    Login or Signup to reply.
  2. const convert = (val) => {
      const plusMinus = val > 0 ? '+' : '-';
      const decimal = val.toFixed(2).replace(/./, ':').replace(/^-/, '');
      const prefixedZero = val < 10 && val > -10 ? '0': '';
      return `${plusMinus}${prefixedZero}${decimal}`
    }
    
    console.log(convert(1.0))
    console.log(convert(-4))
    console.log(convert(0))
    console.log(convert(-10))
       console.log(convert(10))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search