ManhCuong
ManhCuong

Reputation: 11

How to change data from null to 0?

My data from db is null. I have divided this data with 1 other data with a value of 0 and the result into NaN.

 $(".js-view-project-year").text(mathRound(response.data.importPhase.allError.allError / response.data.importPhase.countError.countError));

I want change data from 0 to NaN

Upvotes: 1

Views: 84

Answers (3)

FZs
FZs

Reputation: 18619

Simply use short circuiting OR!

This will return the first value if it truthy, else (in case of 0 or NaN) the second (which is 0).

mathRound(response.data.importPhase.allError.allError / response.data.importPhase.countError.countError) || 0

Upvotes: 0

Aniket Kulkarni
Aniket Kulkarni

Reputation: 12983

Initialize result = 0 this is when you want DB returns null value.

Then check value returned by DB is not false, null, Nan. If yes then and then use in division.

In JavaScript when you use if and the expression is one of the following false, null, Nan, undefined then it results into false.

let result = 0;
if(response.data.importPhase.countError.countError){
   result = mathRound(response.data.importPhase.allError.allError / response.data.importPhase.countError.countError) 
}

Upvotes: 0

Nidhin Joseph
Nidhin Joseph

Reputation: 10237

You can use the isNaN to check if your result is NaN

result = mathRound(allError / countError)

isNaN(result) ? '0' : result;

Upvotes: 1

Related Questions