I'm sending the number/string 0.001 to a the function below:
SignificantFigures = 4;
function LimitNumberOfDigits(num) {
var tempStr = "";
if (isNaN(num))
return "\xD8";
else{
if (parseFloat(num) === 0 || (num.toString().indexOf('.') === -1 && parseInt(num) < 9999) || num.toString().length <= 4) {
return num;
}
tempStr = parseFloat(num).toPrecision(SignificantFigures);
if (tempStr.indexOf("e") > -1) {
var startE = tempStr.indexOf("e");
var endE = 0;
for (var i = startE +2 ; i < tempStr.length; i++ ) { // + to ignore e and sign (+ or - )
if(parseInt(tempStr[i], 10) > 0) {
endE = i;
}else {
break;
}
}
if (startE + 2 === endE) {
var pow = tempStr[endE];
} else {
var pow = tempStr.substring(startE +2 ,endE);
}
return tempStr.substring(0,startE) + "*10<sup>"+ pow +"</sup>";
}else {
return parseFloat(num).toPrecision(SignificantFigures);
}
}
}
When im sending 0.2 or even 0.11 im getting like 0.2000 and 0.1100.
The issue here is the toPrecision acts like ToFixed.
Ideas?
EDIT
What i want? simple as that, if a numbers needs to be changed e.g 0.012312312041 it should be 0.0123 , numbers like 0.12 or 28 should stay the same.
Related
I'm trying to create a cs50 card validator with JavaScript. I'm having problems with the checksum counting. It should be sum % 10 === 0 //true.
let cards = [378282246310005, 371449635398431,
5555555555554444, 5105105105105100, 4012888888881881,
4012888888881880, 1234567890, 361049635398431], result = '';
cards.forEach( card => {
if (isCardValid(card)) {
result += card + ' = ';
checkBank(card);
}
});
document.getElementById('task6').innerHTML = result;
function checkBank(card) {
if ((card >= 340000000000000 && card < 350000000000000) || (card >= 370000000000000 && card < 380000000000000))
result += ("AMEX\n");
else if (card >= 5100000000000000 && card < 5600000000000000)
result += ("MASTERCARD\n");
else if ((card >= 4000000000000 && card < 5000000000000) || (card >= 4000000000000000 && card < 5000000000000000))
result += ("VISA\n");
else
result += ("INVALID\n");
}
function isCardValid(digits) {
let sum = 0;
for (let i = 0; i < digits.length; i++) {
let cardNum = parseInt(digits[i]);
if ((digits.length - i) % 2 === 0) {
cardNum = cardNum * 2;
if (cardNum > 9) {
cardNum = cardNum - 9;
}
}
sum += cardNum;
}
return sum % 10 === 0;
}
Here is some data to check validator work:
378282246310005 //AMEX
371449635398431 //AMEX
5555555555554444 //MASTERCARD
5105105105105100 //MASTERCARD
4012888888881881 //VISA
4012888888881880 //INVALID
1234567890 //INVALID
361049635398431 //INVALID
The main thing is, i can't use strings, arrays and any ready to use functions. Waiting for your help, thanks.
UPD
I solved the issue with an algorithm except for this card:
4012888888881880 //INVALID
My code thinks that this is a VISA card. Bank validation looks fine, so i don't know where to find the problem. Any suggestions where is problem?
UPD2
Final version
let cards = [378282246310005, 371449635398431,
5555555555554444, 5105105105105100, 4012888888881881,
4012888888881880, 1234567890, 361049635398431], result = '';
cards.forEach( card => {
if (isCardValid(card)) {
result += card + ' = ';
checkBank(card);
} else {
result += card + ' = INVALID Card\n'
}
});
document.getElementById('task6').innerHTML = result;
function checkBank(card) {
if ((card >= 340000000000000 && card < 350000000000000) || (card >= 370000000000000 && card < 380000000000000))
result += ("AMEX\n");
else if (card >= 5100000000000000 && card < 5600000000000000)
result += ("MASTERCARD\n");
else if ((card >= 4000000000000 && card < 5000000000000) || (card >= 4000000000000000 && card < 5000000000000000))
result += ("VISA\n");
else
result += ("INVALID Bank\n");
}
function isCardValid(card) {
let sum = 0, len, first = 0, second = 0;
for (len=0; card; Math.floor(card /= 10), ++len) {
let digit = Math.floor(card % 10);
second = first;
first = digit;
if (len & 1) {
digit += digit;
if (digit > 9) {
digit -= 9;
}
}
sum += digit;
}
return sum % 10 === 0;
}
<pre id="task6"></pre>
I want to implement a function in Google Spreadsheet using JavaScript. I have:
var s1 = "000000000000"; // (12 zeros)
var n1 = 1;
I have a third number between 1 and 12. If my number is 6 the result would need to be: 111111000000. If my number is 8 the result would need to be 111111110000.
So far I got stuck here:
function REP(b1) {
var s1 = "000000000000" ;
var n1 = 1;
if (b1 >=1 && b1 <= 12) {
return s1.split("0").join(n1) ;
}
else{
return "no value" ;
}
}
I prefer a simple approach:
function rep(b1) {
var s1 = "000000000000";
var s2 = "111111111111";
if (b1 >=1 && b1 <= 12) {
return s2.slice(0, b1) + s1.slice(b1);
} else {
return "no value";
}
}
console.log(rep(6)); // 111111000000
console.log(rep(8)); // 111111110000
const replacement = "1"
function replaceZeros(n) {
var result = "000000000000"
while (n --> 0) { // it actually mean `n-- > 0`, but it looks cooler that way
result = result.replace(/0/, replacement)
}
return result
}
This simply replaces the first 0 in the string n times.
See demo on JS Bin.
interesting. i would try
function REP(b1) {
var ret = ""
for (var i = 0; i < 12; i++){
if(i < b1){
ret += "1";
}
else{
ret += "0";
}
}
return ret;
}
hrm... there might be a nicer way though...
EDIT: oh yeah, i think you can do:
function REP(b1) {
if(isNaN(b1) || b1 < 1 || b1 > 12){
return 'no answer';
}
return "1".repeat(b1) + "0".repeat(12-b1);
}
you can use Array.join to repeat characters
see following example...
alert(REP(6));
function REP(b1) {
var s1 = "000000000000";
var n1 = 1;
if (b1 >=1 && b1 <= 12) {
return (Array(b1 + 1).join(n1) + s1).substr(0, 12);
} else{
return "no value" ;
}
}
Not sure how performant this is but here's a regex method.
function REP(b1) {
if (b1 < 1 || b1 > 12) return 'no value';
var rx = new RegExp('0{' + b1 + '}');
return '000000000000'.replace(rx, Array(b1 + 1).join(1));
}
DEMO
JavaScript:
var UI; // Number entered by user
var TV; // Number value to be used in calculations
var HITS; // Counter
var DD; // Division denominator
UI = window.prompt("Enter a whole number to be tested as a prime number", "0");
TV = parseInt("UI", [10]);
HITS = 0;
DD = TV;
while (DD > 0) {
if (TV % DD == 0) {
HITS++
}
HITS--
}
window.document.write(+UI + " is ");
if (HITS > 2) {
window.document.write(" not");
}
window.document.write(" a prime number.");
Can anyone tell me what I'm doing wrong? Everything runs except when it isn't a prime number it the "not" string won't come up. Any help is greatly appreciated.
UI = window.prompt("Enter a whole number to be tested as a prime number", "0");
TV = parseInt(UI,10);
HITS = 0;
DD = TV;
while(DD>0) {
if (TV%DD===0) {
HITS++; }
DD--;
}
I changed this much of and it works now.
//FOR user FOON
PrimeNumber=function(){
var d, l, primelist;
_isPrimeNumber = function(n){
var result = true;
_setVariables(n);
while( d < l ){
if(n % d == 0){
result = false;
break;
}
do{
d = d + 1;
}while(!_check(d));
primelist.push(d);
l = n/d;
}
return result;
};
_getAllPrimeTill = function(n){
_setVariables(n);
while( d < n ){
d = d + 1;
if(_check(d)){
primelist.push(d);
}
}
return primelist;
};
_setVariables = function(n){
d=2;
l=n/2;
primelist = new Array();
primelist.push(d);
};
_check = function(n){
var result = true;
for(var i = 0; i < primelist.length; i++){
if(n % primelist[i] == 0 ){
result = false;
break;
}
}
return result;
};
return {
isPrimeNumber :_isPrimeNumber,
getAllPrimeTill : _getAllPrimeTill
};
}();
You have:
DD = TV;
// The value of DD is tested, but not modified in the loop
while(DD>0) {
// This part is irrelevant to the test
if (TV%DD == 0) {
HITS++
}
HITS--
}
DD is not modified in the loop, so if the condition is true or false, it will always be true or false. So if DD is any value greater than zero, the condition is always true.
import java.util.ArrayList;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*if you want to find all prime numbers between 2 and n, change loop "while( d < l ){" to "while( d < n ){" and you will get al prime numbers in primelist.
*/
/**
*
* #author hp
*/
public class PrimeNumber {
public static void main(String[] args) {
String result = " IS A PRIME NUMBER";
int n = 127;
int d = 2;
int l = n / 2;
List <Integer> primelist = new ArrayList<Integer>();
while( d < l ){
if(n % d == 0){
//System.out.println();
//System.out.println(n + " can be divided by " + d);
//System.out.println(d + " * " + (n / d) + " = " + n);
result = " IS NOT A PRIME NUMBER";
break;
}
do{
d = d + 1;
}while(!isPrimeNumber(d,primelist));
//System.out.print(d + ", ");
primelist.add(new Integer(d));
l = n/d;
}
//System.out.println();
System.out.println(n + result);
}
private static boolean isPrimeNumber(int n, List <Integer> primelist){
boolean result = true;
for(Integer i : primelist){
if(n % i.intValue() == 0 ){
result = false;
}
}
return result;
}
}
This question already has answers here:
How do you convert numbers between different bases in JavaScript?
(21 answers)
Closed 1 year ago.
In JavaScript, is there any built-in function for converting an integer from one given base to another given base? I've noticed that it's already possible to convert a decimal number to another base using toString(numberToConvertTo), but I haven't yet found a general-purpose function that can convert from any base to any other base, as shown:
convertFrom(toConvert, baseToConvertFrom, baseToConvertTo){
//convert the number from baseToConvertFrom to BaseToConvertTo
}
Call parseInt(str, fromBase) to convert to base 10 (or rather, to an actual number), then call num.toString(toBase).
You might want to customise your input or output. You might want more than 36 bases. So I made this
function baseCon(number,fromBase,toBase,fromChars,toChars) {
if (!fromChars) {
fromChars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
number = number.toString().toUpperCase();
}
if (!toChars) {
toChars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
}
if (typeof number != 'object') {
number = number.toString();
}
if (fromBase > fromChars.length) {
console.log('fromBase was too high');
} else if (toBase > toChars.length) {
console.log('toBase was too high');
} else {
if (fromBase == 10) {
var base10Num = Math.min(number);
} else {
var base10Num = 0;
var place = 0;
for (var index = number.length - 1; index > -1; index--) {
base10Num = base10Num + (fromChars.indexOf(number[index]) * Math.pow(fromBase,place));
place++;
}
}
var string = '';
var looping = true;
var stringLen = 0;
var stringVal = 0;
while (looping) {
stringLen++;
if (Math.pow(toBase,stringLen) == base10Num) {
stringLen++;
break;
} else if (Math.pow(toBase,stringLen) >= base10Num) {
break;
}
}
for (var placePos = stringLen; placePos > 0; placePos--) {
for (var placeVal = 0; placeVal < (toBase + 1); placeVal++) {
if (((placeVal * Math.pow(toBase,placePos - 1)) > (base10Num - stringVal)) || (placeVal == 0) && ((base10Num - stringVal) == 0)) {
if (!((placeVal == 0) && ((base10Num - stringVal) == 0))) {
stringVal = stringVal + ((placeVal - 1) * Math.pow(toBase,placePos - 1));
string = string + toChars[placeVal - 1];
} else {
string = string + toChars[0];
}
break;
}
}
}
if (stringVal == base10Num) {
return string;
} else {
console.log('baseCon failed');
return string;
}
}
};
You can customise the input chars so you can do things like this
> baseCon([true,true,false,true,false],2,10,[false,true]);
< "26"
and of coarse the output chars
> baseCon('3942',10,8,false,['!','#','#','$','%','^','&','*']);
< "*^%&"
It took me all day and then I remembered parseInt(number,fromBase).toString(toBase); haha
I need to a function to convert an integer to the equivalent alpha ordered list index. For example:
1 = a
2 = b
.
.
.
26 = z
27 = aa
28 = ab
.
.
etc.
Currently I have the following which almost works but there's a small logic error somewhere that makes it not quite get it right (it goes ax, ay, bz, ba, bb, bc...):
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = '',
place,
num,
i;
for ( i = 0; Math.pow(alphaMax, i) < int; i++ ) {
place = Math.pow(alphaMax, i);
num = Math.floor( ( int / place ) % alphaMax);
asciiCode = ( num == 0 ? alphaMax : num ) + asciiStart - 1;
char = String.fromCharCode(asciiCode);
alpha = char + alpha;
}
return alpha;
}
for (i = 1; i < 300; i++) {
console.log( i + ': ' + intToAlpha(i) );
}
This function is used in NVu/Kompozer/SeaMonkey Composer, with a small tweak to generate lower case directly:
function ConvertArabicToLetters(num)
{
var letters = "";
while (num > 0) {
num--;
letters = String.fromCharCode(97 + (num % 26)) + letters;
num = Math.floor(num / 26);
}
return letters;
}
You need to make sure that you use the correct value when taking the mod.
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = "";
while(int > 0) {
char = String.fromCharCode(asciiStart + ((int-1) % alphaMax));
alpha = char + alpha;
int = Math.floor((int-1)/26);
}
return alpha;
}
A while back I needed the same thing in SQL, so I asked (and answered) the question Multi-base conversion - using all combinations for URL shortener.
The thing that is making it complicated is that it's not a straight base conversion, as there is no character representing the zero digit.
I converted the SQL function into Javascript:
function tinyEncode(id) {
var code, value, adder;
var chars = 'abcdefghijklmnopqrstuvwxyz';
if (id <= chars.length) {
code = chars.substr(id - 1, 1);
} else {
id--;
value = chars.length;
adder = 0;
while (id >= value * (chars.length + 1) + adder) {
adder += value;
value *= chars.length;
}
code = chars.substr(Math.floor((id - adder) / value) - 1, 1);
id = (id - adder) % value;
while (value > 1) {
value = Math.floor(value / chars.length);
code += chars.substr(Math.floor(id / value), 1);
id = id % value;
}
}
return code;
}
Demo: http://jsfiddle.net/Guffa/mstBe/