Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I was asked to write code that helps to go from base 10 to any other base. So far I have this
var y=23 //Number in base 10 I want to convert
var x=2 //Base I want to convert to
var r=[]
if(y>=x){
r.push(y%x)
var y=(Math.floor(y/x))
}
else {
r.push(y)
}
console.log(r)
Sorry if this is to basic i need to keep it simple thanks for the help
Use these codes:
var digits = [
'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'
];
/**
* x is the base, y is the decimal value
* x must be in the range of 2..36
* y must be greater than zero
*/
function base10ToBaseN(x,y) {
var str = "";
while (y>0) {
var mod = y%x;
var div = Math.floor(y/x);
str = digits[mod]+str;
y = div;
}
return str;
}
alert(base10ToBaseN(2,23));
See this jsfiddle: http://jsfiddle.net/jondinham/mLz5ycey
function convertToBase(input, base){
var digits = [];
while(digits.push(letter(input%base)), input = (input/base)|0) //work for int
function letter(n){ return n > 9 ? String.fromCharCode(n%base+55) : n;}
return digits.reverse().join("");
}
convertToBase(255,16); //FF
convertToBase(255,2); //11111111
You can even attach this to the Number prototype for extra fun.
Number.prototype._ = function(b){ return convertToBase(this, b); };
255.._(16); //FF
255.._(2); //11111111
//Doesn't look like JavaScript's syntax anymore :)
However note that this only work for ∀n ∈ ℤ, n ≥ 0. Demo: http://jsfiddle.net/DerekL/nxf6wpkz/
Why do mathematicians claim that Halloween is the same as Christmas?
Because convertToBase(25, 8).
Oct 31 = Dec 25
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Is there any way or any library out there that can compute a JS RegEx from a set of strings that I want to be matched?
For example, I have this set of strings:
abc123
abc212
And generate abc\d\d\d ?
Or this set:
aba111
abb111
abc
And generate ab. ?
Note that I don't need a very precise RegEx, I just want one that can do strings, . and .*
Not without producing all the possible outcomes of a certain Grammar, some of which are infinite. This means it's not possible in the general case for finding a specific wanted grammar from a given input set. Even in your cases, you need to give every possible production of the Grammar (regular expression) in order to know exactly what regular expression you are happening to look for. For example the first set, there are several regular expressions that can match it, some of which could be:
abc[0-9][0-9][0-9]
abc[1-2][0-5][2-3]
abc[1-2][0-5][2-3]a*
abc\d*
abc\d+
abc\d+a*b*c*
...
And so on. That being said you could find a grammar that happens to match that sets conditions. One way is to simply brute-force the similarities and differences of each input item. So to do this with the second example:
aba111
abb111
abc
The ab part is the same for all of them so we start with ab as the regexp. Then the next character can be a, b or c so we can say (a|b|c). Then 1 or empty three times. That would result in:
ab(a|b|c)(1|)(1|)(1|)
Which is a correct regular expression, but maybe not the one you wanted.
May be this is too simple but you can use this,
var arr = ['abc121','abc212','cem23'];
var regex_arr = [];
arr.sort(function(a, b){return -a.length+b.length;});
for(var i in arr[0]){
for(var j in arr){
if(i>=arr[j].length){
regex_arr[i] = {value:'',reg:'*',use_self:false};
}else{
var c = arr[j][i];
var current_r = '.';
if(isNaN(c)){
if(/^[A-Za-z]$/.test(c)){
current_r = '\\w';
}else{
current_r = '\\W';
}
//... may be more control
}else{
current_r = '\\d';
}
if(!regex_arr[i]){
regex_arr[i] = {value:c,reg:current_r,use_self:true};
}else{
if(regex_arr[i].value!=c){
if(regex_arr[i].reg!=current_r){
regex_arr[i].reg = '.';
}
regex_arr[i].use_self = false;
regex_arr[i].value = c;
}
}
}
}
}
var result = '';
for(var i in regex_arr){
if(regex_arr[i].use_self){
result += regex_arr[i].value;
}else{
result += regex_arr[i].reg;
}
if(regex_arr[i].reg=='*'){
break;
}
}
console.log("regex = "+result);
for(var i in arr){
var r = new RegExp(result);
console.log(arr[i] + ' = '+r.test(arr[i]));
}
Results
regex = \w\w\w\d\d*
abc121 = true
abc212 = true
cem23 = true
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I am building an angular app involving large amounts. I'd like to shorten the way their are displayed so I built a quick and dirty filter replacing '1000000000' by '$1.0Bn' for example but it is really dirty and it just truncate the numbers instead of rounding them up.
Here it is:
.filter('largeAmountCurrency', function() {
return function(input) {
if (!input) return;
var oneBillion = 1000000000,
oneMillion = 1000000;
if (input > oneBillion)
return '$' + parseInt(input / oneBillion) + '.' +
String(parseInt(input - parseInt(input/oneBillion))).substring(1,3) + 'Bn';
if (input > oneMillion)
return '$' + parseInt(input / oneMillion) + '.' +
String(parseInt(input - parseInt(input/oneMillion))).substring(1,3) + 'M';
return input;
}
});
Is their any prebuilt filter in angular which does this job? Or how can I shorten it dramatically?
You can compute a few things using Mathematical logarithm log!. This will help you knowing the number of digits your input has.
Example (log is base 10 logarithm, ln is napierian logarithm) :
log(12345678910) = ln(12345678910)/ln(10) = 10
Here, 10 is the number of digits after the first '1'.
Based on this information you can compute a simplified value, and then round it with toFixed! (This works with IE5.5+, Javascript 1.5, I assumed you get it when you use AngularJS)
A complete example below :
var number = 12345678910;
var digits = 2;
var suffix = ["", "K.", "M.", "B."];
var nbDigits = Math.round(Math.log(number)/Math.LN10);
var power = nbDigits - nbDigits%3;
var tmp = number/ Math.pow(10, power);
var suffixIndex = Math.min(3, power/3);
var result = "$" + tmp.toFixed(digits) + " " + suffix[suffixIndex];
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I would like to extract the number "40" from following two lines:
Total Boys:4 (40 min)
Main Students:0 (0 min)
How can I do that using javascript? Thank in advance!
Or without a regex
str.split('min').shift().split('(').pop().trim();
FIDDLE
Simply use a regular expression:
var str = 'Total Boys:4 (40 min)\nMain Students: 0 (0 min)';
var number = str.match(/\((\d+)/)[1]; // 40
Here's a simple regex to pull that value out:
var str = 'Total Boys:4 (40 min)\nMain Students:0 (0 min)';
var regexp = /.*\((\d+) min\)\n.*/;
var matches = regexp.exec(str);
alert('match: ' + matches[1]);
Another way of doing it would be simply str.match(/\d+/g)[1] using regex.
DEMO
suppose you have your string inside str andyou want to store the number inside n
another approach is this:
var index1,
index2,
index3,
n;
index1 = str.indexOf('Total Boys:', 0);
index2 = str.indexOf('(', index1) + 1;
index3 = str.indexOf(' ', index2);
n = str.substring(index2, index3);
note that this approach will get only the min value of "Total Boys", not "Main Students".
It will work even if you have another similar line before "Total Boys"
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What I want to do is been available to allow user to only enter 12 hour time am/pm in a a field.
Extra: Any way i can validate 2 fields "from - to", for example: if user enter 1pm in the field from, the field call to will only allow from 1pm and forward.
Any help will be truly appertained. Thanks
You just need some code to parse the string and find problems. logic like this
Does it contain a AM or PM (case insesensitive)
Does it have a : and if it does then pull in the minutes, if not then asume it's only the hours.
are there only numbers before the PM/AM? if not it's invalid.
are any of the numbers greater than 12 or smaller than 1?
some usefull functions would probably be.
"string split".split(" "); // split into an array by spaces
Javascript Equivalent to PHP Explode()
"find the PM".indexOf('PM'); // return turns how many characters
//away the PM is from the left.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
as well as slice()
"slice after PM".slice(6); //this will slice from the beginning to the 6th character.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
DEMO
timepicker
i made it few months back this will help you.
$('#time2').attr('disabled', true);
$("#time").timepicker({
timeOnly: true,
timeFormat: 'hh:mm tt'
}).change(function () {
var val = this.value;
if (val !== '') {
var min = val.split(':');
var min1 = min[1].split(' ');
var minMin = parseInt(min1[0]);
var minHour = ((min1[1] == 'am') ? parseInt(min[0]) : parseInt(min[0]) + 12);
$('#time2').removeAttr('disabled').removeClass('hasDatepicker').timepicker({
timeOnly: true,
timeFormat: 'hh:mm tt',
hourMin: minHour,
}).change(function () {
var val_to = this.value;
var min_to = val_to.split(':');
var min1_to = min_to[1].split(' ');
var minMin_to = parseInt(min1_to[0]);
var minHour_to = ((min1_to[1] == 'am') ? parseInt(min_to[0]) : parseInt(min_to[0]) + 12);
if(minHour_to == minHour && minMin_to <= minMin){
this.value = val;
}
});
} else {
$('#time2').attr('disabled', true);
}
});
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
For example :
Var1 = 289.56
I use this formula :
foundStr = Var1.match("[0-9]+\.[0-9]+");
Price( parseFloat(foundStr).toFixed(2) );
But when Var1 > 999.99 (Example : 2,356.21)
What is the script find the string ?
foundStr = Var1.match(??);
Thank you
You already have a numeric variable, why are you messing with strings?
var number1 = 289.56;
if (number1 > 999.99) {
// do whatever
}
If you're trying to round, use Math.floor instead:
var number1 = 289.56485345734593453;
var roundedNumber1 = Math.floor(number1 * 10) / 10; // two decimal points
I think you just want to remove the commas and check if its a float, but its hard to tell based off your question. How about something like this:
var Var1 = "1,234.567";
var parsed = parseFloat(Var1.replace(",",""), 10);
if (isNaN(parsed)) {
// its not a valid number, so deal with it as needed
}
else {
// parsed now holds your Number, so use it
}
This approach will work regardless of if the number is >= 1000.
var Var1 = "2,356.21";
foundStr = String(Var1.match(/([0-9]{1,3},)?[0-9]{0,3}\.[0-9]+/g)).replace(/,/g, "");
var result = parseFloat(foundStr).toFixed(2);