I am trying to make a program which is able to do both decimal to binary and binary to decimal conversions.
I am having trouble with the binary to decimal portion of the code. Forgive me as I know the coding is quite incomplete but I can't figure out where I am going wrong.
Currently I am getting partially correct output in the calculation field (ex. "there is a 1 in the value of (2^0)" and "there is a 2 in the value of (2^1)").
However, when I type 11 as decimal the calculation field is repeating the code twice
(ex. "there is a 1 in the value of (2^0)","there is a 2 in the value of (2^1)","there is a 1 in the value of (2^0)", "there is a 2 in the value of (2^1)").
Obviously it should only give those values once per number.
Also the output field for the actual binary number is incorrect as well, and some of the variables aren't utilized/not needed, but I have been trying to fix the problem of repeating values first before I worked on that.
Any help would be much appreciated!!
function convertByArray(bval) {
var rB = new Array();
var outstr = "";
var p, t, a, o;
o = 0;
for(var i=0; i<bval.length; i++) {
var b = bval.charCodeAt(i);
t = 2;
p = i;
a = t ** p;
if(a === t ** p) {
outstr += a;
}
var bV = b;
$("txtCalc").value += "There is a " + a + " in the value " + "(" + t + "^" + p + ")" + "\n";
o += 1;
b = bV;
$("txtOut").value = outstr;
}
}
You can simply your code if you access the most-significant bit of the bit-string by taking the length (minus one) and subtracting it from the current position. You can access string characters like an array.
var $txtCalc = $(".txtCalc");
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function binaryToDecimal(bval) {
var base = 2, result = 0;
for (var pos = 0; pos < bval.length; pos++) {
var bit = +bval[(bval.length - 1) - pos];
if (bit === 1) {
result += base ** pos;
}
var message = "There is a " + bit + " in the position (" + base + "^" + pos + ")";
$txtCalc.val($txtCalc.val() + message + "\n");
}
$txtOut.val(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />
<br />
<textarea class="txtCalc" rows="10" cols="60"></textarea>
Alternatively, you can simply your program to the following. In JavaScript, you can parse any number in any base and format to another base.
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function convertFromBaseToBase(number, fromBase, toBase) {
return parseInt(number, fromBase).toString(toBase);
}
function binaryToDecimal(bval) {
$txtOut.val(convertFromBaseToBase(bval, 2, 10));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />
Related
I gave an example of using .tofixed() with math, functions, and arrays, to a beginner coder friend who has been reviewing these topics in his class.
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
};
bananaDivision();
They were understanding and following along no problem.
Then they asked me - "What if we put a decimal in the .toFixed ?"
So I ran:
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
let bananaFixed1 = bananaDivided.toFixed(.69420);
let bananaFixed2 = bananaDivided.toFixed(1.69420);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
console.log("After using .toFixed(.69420) : " + bananaFixed1 + '\n');
console.log("After using .toFixed(1.69420) : " + bananaFixed2 + '\n');
};
bananaDivision();
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
Am I correct? For my own curiousity, is there a crazy way to break .toFixed() so that it actually uses decimals? I'm experimenting atm but wanted to know if someone already figured that out.
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
This would be correct. That is essentially what happens.
For full correctness, the input of toFixed() will be converted to an integer. The specification states that the argument must first be converted to a number - NaN will be converted to a zero. Numbers with a fractional part will be rounded down.
Which means that if you pass any number, you essentially get the integer part of it.
It also means that non-numbers can be used:
const n = 3;
console.log(n.toFixed("1e1")); // 1e1 scientific notation for 10
You're close, since toFixed() expects an integer it will handle converting decimal numbers before doing anything else. It uses toIntegerOrInfinity() to do that, which itself uses floor() so the number is always rounded down.
Most of Javascript handles type conversion implicitly, so it's something you should really understand well if you don't want to run into problems. There's a free book series that explains that concept and a lot of other important Javascript knowledge very well, it's called You Don't Know JS Yet.
just a demo how .tofixed works !!!!!!
function roundFloat(x, digits) {
const arr = x.toString().split(".")
if (arr.length < 2) {
return x
}else if(arr[1] === ""){
return arr[0]
}else if(digits < 1){
return arr[0]
}
const st = parseInt(x.toString().split(".")[1]);
let add = false;
const rudgt = digits
const fX = parseInt(st.toString().split("")[rudgt]);
fX > 5 ? add = true : add = false
nFloat = parseInt(st.toString().split("").slice(0, rudgt).join(""))
if (add) {
nFloat += 1
}
const repeat0 = (() => {
if (rudgt - st.toString().length < 0) {
return 0
}
return rudgt - st.toString().length
})()
const output = x.toString().split(".")[0] + "." + nFloat.toString() + "0".repeat(repeat0);
return output
}
console.log(roundFloat(1.200, 2))
I have a program that reads a specific text file from a coding challenge that I've recieved and it takes the numbers and puts it into an array for me to solve a quadratic equation. When I go to display my answers I keep getting the NaN error on all of my values and I cant find where I messed up.
CODE
var lines = data[0].split("/n");
var numQuads = lines[0];
for (var i = 1; i < numQuads; i++){
var fields = lines[i].split(",");
var a = fields[0];
var b = fields[1];
var c = fields[2];
}
a = parseInt();
b = parseInt();
c = parseInt();
var discr = (b * b) - (4 * (a * c));
var sqrDiscr = Math.sqrt(discr);
var x = (-b + sqrDiscr) / (2*a);
var y = (-b - sqrDiscr) / (2*a);
var outputL = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has no real roots!";
var outputW = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has roots x = " + x + " and x = " + y;
if (discr >= 0) {
output += outputW + "\n";
}
else {
output += outputL + "\n\n";
}
You did not provide an argument to the parseInt function. It works like this: parseInt("2") for example. You probably want to use parseFloat instead of parseInt.
Another remark: your data array is undefined.
you have insert String in parseInt()
a = parseInt("67");
b = parseInt("3");
c = parseInt("2");
Should probably be:
a = parseInt(a);
b = parseInt(b);
c = parseInt(c);
the problem was var lines = data[0].split("/n");
I used the wrong character. It was supposed to be var lines = data[0].split("\n");
The problem is that you are not parsing anything with your parse int.
Take a look here for some docs on parseInt.
Anyway that's how it should look like in your code:
a = parseInt(a, 10);
b = parseInt(b, 10);
c = parseInt(c, 10);
d = parseInt(d, 10);
EDIT: following the suggestion of #d3l I looked into the parseInt parameters, according to this question there could be some unexpected behaviours of the parseInt function without adding the radix parameter. Hence I added it to my solution.
Assuming you are parsing integers we can specify 10 as base.
all! recently i've been trying to build a mercende prime number producer/generator, using the lucas lehmer method of testing. the code works for the first 4 numbers, and then fails for the rest. any suggestions? thanks!
var totalPrimes = Math.floor(prompt("What would you like the upper limit of
our search for primes to be?"));
for (var i = 2; i < totalPrimes; i++) {
var lucasNum = 4;
var curNumber = (Math.pow(2, (i+1))-1);
for (var x = 0; i-1 > x; x++) {
if (lucasNum / curNumber > 1) {
lucasNum = (Math.pow(lucasNum, 2)-2);
} else {
lucasNum = (Math.pow(lucasNum, 2)-2);
}
}
if (lucasNum % curNumber === 0) {
console.log("The number " + curNumber + " is prime");
} else {
console.log("The number " + curNumber + " is not prime");
}
}
The mantissa (or significand) of a Javascript number is 53-bit wide. Therefore, the biggest integer that can be stored in full precision is:
2^53 - 1 = 9007199254740991 = Number.MAX_SAFE_INTEGER
(You may want to read this page for more details.)
Your algorithm is likely to hit this limit very quickly. The precision explosion occurs within this statement:
lucasNum = (Math.pow(lucasNum, 2)-2);
which is included in a loop.
I need to write a javascript program that will ask the user to enter a string of lower‐case
characters and then print its corresponding two‐digit code. For example, if
the input is “home”, the output should be 08151305.
So far I can get it to return the correct numbers, but I cannot get it to add the zero in front of the number if it is a single digit
This is what I have:
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name = prompt("Please enter a string of lowercase characters");
document.write(name,'<br>');
document.write('Length of the input is ', name.length,'<br>');
document.write("<br>")
for (i=0; i < name.length; i++)
{
{
document.write(i, ", ",name.charCodeAt(i) - 96, '<br>');
}
}
}
</script>
</head>
<body>
<input type="button" onClick="show_prompt()"value="CSE 201 HW#4 Problem 3"/>
</body>
</html>
Well you can just check if it is a single digit and if so prepend "0":
function padToTwoDigits(c) {
// convert to string and check length
c = "" + c;
return c.length === 1 ? "0" + c : c;
// or work with it as a number:
return c >=0 && c <=9 ? "0" + c : c;
}
// then within your existing code
document.write(i, ", ",padToTwoDigits(name.charCodeAt(i) - 96), '<br>');
Of course those are just some ideas to get you started. You can pretty that up somewhat, e.g., you might create a more generic pad function with a parameter to say how many digits to pad to.
You can write your own pad function such as:
function pad(number) {
return (number < 10 ? '0' : '') + number
}
and use the pad function like:
document.write(i, ", ",pad(name.charCodeAt(i) - 96), '<br>');
Try this.
function show_prompt() {
var name = prompt("Please enter a string of lowercase characters");
document.write(name, '<br>');
document.write('Length of the input is ', name.length, '<br>');
document.write("<br>")
for (i = 0; i < name.length; i++) {
var n = name.charCodeAt(i) - 96;
document.write(i, ", ", n < 10 ? "0" + n : n, '<br>');
}
}
I wrote up a quick sample here:
http://jsfiddle.net/ZPvZ8/3/
I wrote up a prototype method to String that handles padding zeros.
String.prototype.pad = function(char, len){
var chars = this.split();
var initialLen = len - this.length;
for(var i = 0; i < initialLen; i++){
chars.unshift(char);
}
return chars.join('');
};
I convert it to an array and then add elements with the padding character. I chose to use an array since performing string manipulations is an expensive operation (expensive in memory and CPU usage).
To use it in your program, you'd just call it like this:
var res = new Array();
for (var i = 0; i < name.length; i++) {
var strCode = (name.charCodeAt(i) - 96).toString();
res.push(strCode.pad('0', 2));
}
document.write(res.join(''));
I have a text input field for a form where users are meant to enter a number. I would like to automatically insert a comma after every third digit.
For example, entering '20' would result in '20'. Entering '100' would result in '100'. But if they were to enter '1000', a comma would be inserted between the 1 and the following 0's (e.g., 1,000). Obviously this behaviour would continue should the number reach 7 digits (e.g., 1,000,000).
Is there an easy way to do this? I'm a bit of a newb at all of this, so please answer like you're talking to a child :)
The following javascript:
function format(input)
{
var nStr = input.value + '';
nStr = nStr.replace( /\,/g, "");
var x = nStr.split( '.' );
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while ( rgx.test(x1) ) {
x1 = x1.replace( rgx, '$1' + ',' + '$2' );
}
input.value = x1 + x2;
}
and the following HTML:
<input type="text" onkeyup="format(this)">
should solve your problem. The key is to use 'onkeyup'.
Try it here http://jsfiddle.net/YUSph/
for the fun of it:
'9876543210'
.split('') // flip the entire string so that we can break every
.reverse() // 3rd digit, starting from the end
.join('')
.split(/(...)/) // split on every 3rd
.reverse() // flip the string again, though now each group of 3 is
.join(',') // backwards
.replace(/,(?=,)|,$|^,/g, '') // remove extra ,
.replace(/(,|^)(\d)(\d)?(\d)?/g, '$1$4$3$2') // flip each group of digits
// 9,876,543,210
Anyone want to take a stab at making that better?
function addCommas(nStr){
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Pass the value of the input into function and set the input with the result returned. You can bind this to an onchange event.
Here is a working example that relies on jquery to bind the change event and set the value: http://jsfiddle.net/TYyfn/
Comma script is from: http://www.mredkj.com/javascript/nfbasic.html
Yes, it's not terribly difficult. I believe this reference may give you what you need.
Note that for this to be dynamic (as they type) you'd need to have this wired to the input field change handler. Otherwise, you can wire this to the input field blur handler (which will have the effect of putting the commas in the field when they leave the field).
Give this a try: it may need a little tweeking.
take the function from above: function addCommas(nStr){...} and put in a js file.
add a script link in the page header to jquery library with:
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"
be sure your text box has a unique id. ex: id="comma_input".
in the same js file add
$(document).ready(function(){
$('#comma_input').keyup(function(){
$(this).attr('value',addCommas($(this).attr('value')));
});
});
function addCommas(nStr){
var offset = nStr.length % 3;
if (offset == 0)
return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})(?=[0-9]+)/g, "$1,");
else
return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})/g, ",$1");
}
alert(addCommas("1234567"));
Another way to do it, no RegEx, just array manipulation:
function decimalMark(s) {
for (var a = s.split("").reverse(), b = [], i = 0; i < a.length; i++) {
if (i && i%3 === 0)
b.unshift(",");
b.unshift(a[i]);
}
return b.join("");
}
Be sure to pass a string to the function
decimalMark("1234")
Simple string solution in pure JS:
function addCommas(e) {
var tgt = e.target, val = tgt.value.replace(/,/g, ''),
amt = Math.ceil(val.length/3), newStr = '', x = 0;
while ( x <= amt ) {
newStr += val.slice(x*3,(x+1)*3);
newStr += ( x < amt-1 ) ? ',' : '';
x++
}
tgt.value = newStr;
}
document.getElementById('test').addEventListener('change', addCommas, false);
Demo: http://jsfiddle.net/kevinvanlierde/TYyfn/141/
You can use standart JavaScript functions. Example here;
http://jsfiddle.net/azur/jD5pa/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>pure js solution</title>
<script type='text/javascript'>
function digitGroup(dInput) {
var output = "";
try {
dInput = dInput.replace(/[^0-9]/g, ""); // remove all chars including spaces, except digits.
var totalSize = dInput.length;
for (var i = totalSize - 1; i > -1; i--) {
output = dInput.charAt(i) + output;
var cnt = totalSize - i;
if (cnt % 3 === 0 && i !== 0) {
output = " " + output; // seperator is " "
}
}
} catch (err)
{
output = dInput; // it won't happen, but it's sweet to catch exceptions.
}
return output;
}
</script>
</head>
<body>
<input type="text" value="53" onkeyup="this.value = digitGroup(this.value);">
</body>
</html>
var formatNumber = function(num, type) {
var numSplit, int, dec, type;
num = Math.abs(num);
num = num.toFixed(2);
numSplit = num.split('.')
int = numSplit[0];
if (int.length >= 3) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3);
}
dec = numSplit[1];
return (type === 'exp'? sign = '-' : '+') + ' ' + int + '.' + dec;
};