简体   繁体   中英

Trying to prepend leading zero and decimal to number Javascript

I'm having some trouble trying to prepend a leading zero and decimal in Javascript whilst maintaining the number format. I'm able to do this successfully as a string, but when trying to utilise a parseInt() , it strips the leading zero and decimal and converts to a whole number.

The end goal I'm trying to achieve is the following:

  1. 0.5000
  2. 0.0500

And, if less numbers are given:

  1. 0.50
  2. 0.05

I have a function that takes a number, and an optional boolean value to determine whether to do the above, utilising a JS switch:

function formatTrainingDigit(number, decimals) {
  var numberSplit = number.toString().split('')
  if (decimals) {
    switch (numberSplit.length) {
      case 1:
        return '0.0' + number // TODO: this returns string, change to number.
        break;
      case 2:
        return '0.' + number // TODO: this returns string, change to number.
        break;
      case 3:
        return '0.' + number // TODO: this returns string, change to number.
        break;
      case 4:
        return '0.' + number // TODO: this returns string, change to number.
        break;
      default:
        return 0.00
    }
  } else {
    switch (numberSplit.length) {
      case 1:
        return 0,0,0,parseInt(numberSplit[0])
        break;
      case 2:
        return 0,0,parseInt(numberSplit[0]),parseInt(numberSplit[1])
        break;
      case 3:
        return 0,parseInt(numberSplit[0]),parseInt(numberSplit[1]),parseInt(numberSplit[2])
        break;
      case 4:
        return parseInt(numberSplit[0]),parseInt(numberSplit[1]),parseInt(numberSplit[2]),parseInt(numberSplit[3])
        break;
      default:
        return 0,0,0,0
    }
  }
}

I'd be passing values into the function as: formatTrainingDigit(5000, false) or formatTrainingDigit(50, true)

However, when trying to then do a parseInt() on my returned function, it strips everything, eg:

This works: console.log(formatTrainingDigit(5000, true)) // returns string This fails: console.log(parseInt(formatTrainingDigit(5000, true))) // returns number zero

You can use toFixed method of number. below is an example.

 function addZeroes( num ) { var value; var res; if(typeof num== "number") { value = (num); res = num.toString().split("."); } else{ value = Number(num); res = num.split("."); } if(res.length == 1 || (res[1].length < 3)) { value = value.toFixed(4); } return value } var ww = '0.01' var xx = 5 var yy = .5 var zz = '4.567' console.log(addZeroes(ww)); console.log(addZeroes(xx)); console.log(addZeroes(yy)); console.log(addZeroes(zz));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM