简体   繁体   中英

Remove decimal values

I want to remove decimal values only if all the decimal values are 0 .

If I use parseFloat() :

50.00 => 50
60.50 => 60.5

My expected output:

50.00 => 50
60.50 => 60.50

I can't use Math.round() , Math.trunk() , Math.floor() , ParseInt() .

Is there any other way?

You can try this:

 const formatTo = n => Number.isInteger(n) ? n : parseFloat(n).toFixed(2); console.log(formatTo(50.00)) console.log(formatTo(60.50)) 

With given string, you could remove all zeroes after the decimal point.

 var values = ['50.00', '60.50']; console.log(values.map(s => s.replace(/\\.0*$/, ''))); 

Well since JavaScript does not support trailing zeros, I assume you are working with numbers and will have to convert them to strings. So in the case you would need to use toFixed() and remove the double zeros

 function trimZeros (num) { return num.toFixed(2).replace(/\\.00/,"") } console.log(50, trimZeros(50)) console.log(60.5, trimZeros(60.5)) console.log(0.5, trimZeros(0.5)) console.log(100.01, trimZeros(100.01)) 

if it is just a string you have, than you can just do a reg exp on it

function trimZeros (numStr) {
  return numStr.replace(/\.00/,"")
}

Use toFixed() and RegEx /[.,]00$/ with replace() like the following:

 var num1 = (50.00).toFixed(2).replace(/[.,]00$/, ""); var num2 = (60.50).toFixed(2).replace(/[.,]00$/, ""); console.log(num1) console.log(num2) 

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