cordova - When and why number evaluates to NaN, after multiplying, in Javascript? -
from experience know, can nan
when doing division or when trying make number out of string, when not contain number. there other situations, when can nan
. in particular -- possible multiplication?
this piece of code, use in phonegap application:
var g = 9.80665; acceleration.x = (acceleration.x * g).tofixed(2); acceleration.y = (acceleration.y * g).tofixed(2); acceleration.z = ((acceleration.z + 1) * g).tofixed(2);
an acceleration
base phonegap object , can hardly believe, contains string or other value, except float, result in nan
.
however, in situations (on specific devices) i'm getting nan
out of above.
it isn't problem me "secure" above values code this:
acceleration.x = (parsefloat(acceleration.x) || 0) + ' m/s\u00b2'; acceleration.y = (parsefloat(acceleration.y) || 0) + ' m/s\u00b2'; acceleration.z = (parsefloat(acceleration.z) || 0) + ' m/s\u00b2';
but, i'm curious, when , why can nan
after doing multiply of values?
btw: i've read this @ mdn, many related answers here @ stack overflow, brought me no or answer question.
you'll nan when multiplying number can't converted number.
1 * '100' // 100 because '100' converted 100 1 * '' // 0 because '' converted 0 1 * 'ten' // nan because 'ten' can't converted number 1 * [] // 0 because [] converted number 0 1 * [123] // 123 because [] 123 1 * ['ten'] // nan 1 * {} // nan 1 * true // 1 because true 1 1 * false // 0 1 * null // 0 1 * undefined // nan, undefined can't converted number 1 * function(){} // nan
the function 'isnan' checks if expression can converted number o not. culd check both numbers of multiplication confirm both numbers avoid errors.
for sake of completeness, know if variable nan must compare itself:
var = nan; if (a != a) console.log('a nan');
it happens because nan defined unequal everything, including itself.
Comments
Post a Comment