In my javascript variable I am getting the value as "abc"
or "123"
or "123.456"
based on the input given in the input
field. For all the values the type is string
even if the entered value is number or float.
typeof(variable)
gives string
always.
The following method will be triggered on each keydown
. I am also using the lodash
library
convertMethod(val) {
console.log(round(val,2).toString()) //round is a lodash method which is imported already
}
When I round
the value the decimal point is not coming. I just want to round the value by two decimal points if the entered value is digits and not alphabets. How can I fix this?
You can check if it number or not using isNaN
. Round it up if it is a number:
convertMethod(val) {
if(!isNaN(val))
console.log(round(val,2).toString())
else
console.log(val)
}
convertMethod("qw")
convertMethod("12.3456")
convertMethod("12.432")
convertMethod("12")
Output:
"qw"
"12.35"
"12.43"
"12"
Try converting the string to a number (via _.toNumber()
or the +
operator. Then check if it's a number using _.isFinite()
which returns false
for non numbers, Infinite, -Infinite, and NaN
.
const { isFinite, round } = _ const convertMethod = val => { if (isFinite(+val)) console.log(round(val, 2).toString()) else console.log(val) } convertMethod('5.4435') convertMethod('abc')
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
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.