简体   繁体   English

JavaScript - 以字符串的形式将十进制数转换为 4 位二进制数

[英]JavaScript - Convert decimal number to 4-bit binary number in the form of String

I wrote a Javascript method that will take a decimal number input and gives a binary number in the form of string.我写了一个 Javascript 方法,它将接受十进制数输入并以字符串的形式给出一个二进制数。

Example 1: Input: 15 Output : "1111" Example 1:输入:15 ​​输出:“1111”

The method I wrote works as follows:我写的方法如下:

If my input number is 15 ,如果我输入的数字是 15

var t = parseInt(15,10).toString(2);

then output of t will be "1111"那么t输出将是“1111”

My question is how to convert a number lesser than 15 also as a 4-bit binary number string.我的问题是如何将小于 15 的数字也转换为 4 位二进制数字字符串。 As in,就像在,

Input: 4输入:4

Desired output : "0100" , but what I get right now is, "100" .所需的输出: "0100"但我现在得到的是 "100"

Please help me with the workaround.请帮助我解决方法。

Use padStart使用padStart

The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. padStart()方法用另一个字符串padStart()当前字符串(多次,如果需要),直到结果字符串达到给定长度。 The padding is applied from the start of the current string.从当前字符串的开头应用填充。

 var t1 = parseInt(4, 10).toString(2).padStart(4, "0") var t2 = parseInt(15, 10).toString(2).padStart(4, "0") console.log(t1) console.log(t2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript 如何将十进制数转换为具有特定小数位数的字符串 - Javascript How to convert a decimal number to a string with specific number of decimal places 我有十进制数字,需要转换为二进制,并有一个复选框链接到该二进制数字的每一位 - I have decimal number, need to convert to binary and have a checkbox linked to every bit of that binary number 将字符串中的负数转换为 JavaScript 中的负十进制数 - Convert negative number in string to negative decimal in JavaScript 使用JavaScript手动将十进制字符串转换为数字 - Manually Convert A Decimal String To A Number Using JavaScript 如何将二进制数转换为带符号的十进制数 - How to convert a binary number into a Signed decimal number 从用户那里收集二进制数并在 JavaScript 中将其转换为十进制 - Collect binary number from user and convert it to decimal in JavaScript 如何在JavaScript中将数字的二进制表示从字符串转换为整数? - How to convert binary representation of number from string to integer number in JavaScript? 在javascript中将十进制数转换为百分比 - Convert a decimal number to percentage in javascript 将货币转换为十进制数 JavaScript - Convert currency to decimal number JavaScript 将字符串转换为 1 行中的 2 个十进制数字 - Convert string to 2 decimal Number in 1 line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM