- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Converting decimal to binary or hex based on a condition in JavaScript
Problem
We are required to write a JavaScript function that takes in a number n. Our function should convert the number to binary or hex based on −
- If a number is even, convert it to binary.
- If a number is odd, convert it to hex.
Example
Following is the code −
const num = 1457; const conditionalConvert = (num = 1) => { const isEven = num % 2 === 0; const toBinary = () => num.toString(2); const toHexadecimal = () => num.toString(16); return isEven ? toBinary() : toHexadecimal(); }; console.log(conditionalConvert(num));
Output
Following is the console output −
5b1
- Related Articles
- Change string based on a condition - JavaScript
- Reorder array based on condition in JavaScript?
- Convert a numeric column to binary factor based on a condition in R data frame
- Converting to hex and summing the numeral part in JavaScript
- Converting string to a binary string - JavaScript
- Adding binary without converting in JavaScript
- Find MongoDB records based on a condition?
- SUM a column based on a condition in MySQL
- Appending a key value pair to an array of dictionary based on a condition in JavaScript?
- Python program to print decimal octal hex and binary of first n numbers
- How to disable a TestNG test based on a condition?
- ORDER BY records in MySQL based on a condition
- How to create a column with binary variable based on a condition of other variable in an R data frame?
- JavaScript algorithm for converting Roman numbers to decimal numbers
- Binary array to corresponding decimal in JavaScript

Advertisements