mardi 30 mars 2021

Adding variable 'flag' if user choses that unit javascript

I have a function where I need to add a second variable that checks if a user selected that unit. If not the code runs the second if statement.

I want my function to check that and be able to let the user change the unit as well. For example if we have the number 3,000 the user can change that number to 3K. If we have the number 3,000,000 the user can change it to 3M.

How can I accomplish that with my current code?

function Formatting (num, flag) {
    if (num >= 1000000000 && flag === 'G') {
       return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
    }
    if (num >= 1000000 && flag === 'M') {
       return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
    }
    if (num >= 1000 && flag === 'K') {
       return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
    }
    return num;
}

Aucun commentaire:

Enregistrer un commentaire