[英]Remove decimal values
I want to remove decimal values only if all the decimal values are 0
. 我只想删除所有十进制值为
0
的十进制值。
If I use parseFloat()
: 如果我使用
parseFloat()
:
50.00 => 50
50.00 => 50
60.50 => 60.560.50 => 60.5
My expected output: 我的预期输出:
50.00 => 50
50.00 => 50
60.50 => 60.5060.50 => 60.50
I can't use Math.round()
, Math.trunk()
, Math.floor()
, ParseInt()
. 我不能使用
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. 好吧,因为JavaScript不支持尾随零,所以我假设您正在使用数字,并且必须将它们转换为字符串。 So in the case you would need to use toFixed() and remove the double zeros
因此,在这种情况下,您需要使用toFixed()并删除双零
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 如果只是一个字符串,那么就可以对其进行reg exp
function trimZeros (numStr) {
return numStr.replace(/\.00/,"")
}
Use toFixed()
and RegEx /[.,]00$/
with replace()
like the following: 如下所示,将
toFixed()
和RegEx /[.,]00$/
与replace()
/[.,]00$/
使用:
var num1 = (50.00).toFixed(2).replace(/[.,]00$/, ""); var num2 = (60.50).toFixed(2).replace(/[.,]00$/, ""); console.log(num1) console.log(num2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.