En mi método de cálculo de porcentajes (), debería obtener 0% en lugar de NULL%.
En mi console.log, obtengo impresiones con los valores NULL
calculatePercents() { this.v.global.total.amount = this.v.global.cash.amount + this.v.global.sec.amount; console.log("Cash => " + JSON.stringify(this.v.global.total.amount)); console.log('------------------------'); this.v.global.cash.percent = (this.v.global.cash.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100; console.log(" Global cash " + JSON.stringify(this.v.global.cash.percent)); this.v.global.sec.percent = (this.v.global.sec.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100; console.log(" NULL ???? ==> " + JSON.stringify(this.v.global.sec.percent)); var totPercent = (this.v.global.cash.percent + this.v.global.sec.percent); this.v.global.total.percent = totPercent; }¿Cómo podría obtener un 0 en lugar de NULL, por favor?
Puedes probar esto en tu método;
if(this.v.global.cash.amount == null){ this.v.global.cash.amount = 0 } if(this.v.global.sec.amount == null){ this.v.global.sec.amount = 0 }Y luego puedes hacer eso; (tu método)
calculatePercents() { this.v.global.total.amount = this.v.global.cash.amount + this.v.global.sec.amount; console.log("Cash => " + JSON.stringify(this.v.global.total.amount)); console.log('------------------------'); this.v.global.cash.percent = (this.v.global.cash.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100; console.log(" Global cash " + JSON.stringify(this.v.global.cash.percent)); this.v.global.sec.percent = (this.v.global.sec.amount / (this.v.global.cash.amount + this.v.global.sec.amount)) * 100; console.log(" NULL ???? ==> " + JSON.stringify(this.v.global.sec.percent)); var totPercent = (this.v.global.cash.percent + this.v.global.sec.percent); this.v.global.total.percent = totPercent;}
Y su verdadero tipo se puede "dejar". Código sencillo:
let a = null; if(a==null){ a=0 } console.log(a); // output: 0con || si el primer valor es falso (convertido como booleano), tomará el segundo, en ese caso se usa como valor predeterminado.
this.v.global.total.percent = totPercent || 0;puedes usar || operador para poner cero
P.ej:
this.v.global.total.percent = (totPercent||0);para más https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR