Check out the number_format function (returns a string): number_format($price, 2); Will return the string "12.50" when $price is set to 12.5...

python,list,python-2.7,tree,numbers

You can use itertools.combination to get the desire pairs and use izip to zip your lists and compare the elements in same index. Also as a more elegant way you can put your lists within a dictionary like following : d={ 'list_1':[13579875, 25732, 3541, 56732, 1567, 20546, 10, 68971], 'list_2'...

You didn't specify your DBMS so here's a TSQL solution that at least shows you a simple method for what you need to do. DECLARE @input VARCHAR(25) = '1213121'; WITH CTE_nums --just a list of numbers from 1 to the length of the input which is 7 in this case...

I'm not sure what is the data type of LAT and LON in your table POSTCODE. But whatever variables you define to fetch data into, they must match these types. For examples, assuming that LAT and LON are of the type NVARCHAR2, then I would rewrite your declaration section as...

r,date,numbers,rstudio,data-type-conversion

You can do this easily with lubridate although it indexes Sunday as '1'. So since March 1, 2014 was a Saturday it would return '7' library(lubridate) wday(mdy("3-1-2014")) [1] 7 ...

You are missing the word return near the end. It should look like this: return reduce($new_number); ...

In your storyboard select the artSizeTextField and remove its formatter.

You can use Math.min and Math.max, and use them in an array to return the result, try: function highestAndLowest(numbers){ numbers = numbers.split(" "); return Math.max.apply(null, numbers) + " " + Math.min.apply(null, numbers) } document.write(highestAndLowest("1 2 3 4 5")) ...

You can take your number that ranges from 0 to 500 and simply divide it by 500, e.g. scaled_x = x / 500.0f. Depending on the language and the type of x you will need to divide by either 500 or 500.0f. If you are using a language that has...

find's -regex matches against the whole path, not just the filename (I myself seem to forget this once for every time I use it). Thus, you can use: find . -regex '.*/[0-9]+\.html' (^ and $ aren't necessary since it always tests against the whole path.) Using find also has advantages...

String functionName(int number){ StringBuilder str = new StringBuilder("{"); for(int i = 1; i <= number; i++){ str.append(Integer.toString(i)).append(", ");} String string = str.toString().trim(); string = string.substring(0, str.length()-1); string += "}"; return string; } This should give you the desired string and you just print it....

javascript,math,numbers,floating

If you're wanting to square a number, it's not x^2 - that's a bitwise xor. You need Math.pow(x, 2)....

You can use JavaScript's arguments inside a function to handle arbitrary number of parameters. var Calculator = { average: function() { var num = 0,length=arguments.length; if(!length) return 0; for (var i = 0; i < length; i++) num = num + arguments[i]; var divide = num/length; return divide; } };...

The integral values of characters '0'...'9' are not 0...9. Hence, change every occurrence of str1[k] to str1[k]-'0'....

java,templates,generics,numbers

Something like this as the base class: public abstract class Addable<T extends Number,U extends Addable<T,U>> { private final T value; public Addable( final T value ){ this.value = value; } public T getValue(){ return value; } public abstract U add( U addend ); } And this as the sub-class: public...

This should work for you: Just replace the space and the comma in your number with str_replace() echo (float) str_replace([" ", ","], ["", "."], $str); output: 3320.17 To get your float number now in your expected format just use number_format(). $str = "3 320,17"; $floatNumber = (float)str_replace([" ", ","], ["",...

java,math,numbers,logic,primes

You first need to parse the string you want (3,6,86,13) for example. For this problem, you can use a regexp (now you have two problems (-:). See http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html. Your regexp needs to parse a parens, following by some digits, then maybe a comma and some more digits multiple times, then...

javascript,jquery,validation,floating-point,numbers

No need for the long code for number input restriction just try this code. It also accepts valid int & float both values. Javascript Approach onload =function(){ var ele = document.querySelectorAll('.number-only')[0]; ele.onkeypress = function(e) { if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false; } ele.onpaste = function(e){ e.preventDefault(); } } <p> Input box that...

Integers that start with zero are consider octal. Because octal integers only use numbers from 0 to 8 everything from the 9 on are ignored. So 00445790 becomes 004457 which is 2351 in decimal....

Your implementation of getting each digit value first, then multiplying by 10 as fit, is a common implementation. For instance, this one from MS, is basically the same as your implementation. In most languages you can get the integer value by subtracting the character '0' from the input character, because...

You can remove the comma and then convert the value to a numeric data type: DECLARE @Number VARCHAR(50); SET @Number = '-128,533.74'; SELECT CONVERT(DECIMAL(16,4),REPLACE(@Number,',','')) ...

The sums of the first ten and 100 fibonacchi number would be 88 and 573147844013817084100, respectively: >>> cache = {} >>> def fib(n): if n == 0: return 0 if n == 1: return 1 if not n in cache: cache[n] = fib(n - 1) + fib(n - 2) return...

First of all, using fflush on stdin is Undefined Behavior as per the C11 standard, although it is well defined on some implementations. Secondly, you can't use simply use isdigit that way. Once %f sees invalid data such as characters, the scanf terminates and the corresponding argument is left untouched....

I finished using this function: onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) return false;" This work well in IE and Chrome, I don´t know why it´s not work well in firefox too, this function block the tab key in Firefox. Thanks for all....

This is a complete code for compression and decompression of positive long integers based on h3n's idea of using 1 byte for 2 characters, thanks! It uses 15 numeral system: from 0000 to 1110 binary and 1111 (0xF) as a separator. compression: public List<byte> EncodeNumbers(List<long> input) { List<byte> bytes =...

javascript,random,numbers,type-conversion

Lose the + signs and you should be fine: function randomGen(){ return (Math.random()*11).toFixed(2) } // console.log(randomGen()) // some times i would get 10.5 when i want 10.50 var num1 = randomGen(); // i want 10.50, for example not 10.5 var num2 = randomGen(); console.log(num1, " ", num2) console.log((num1 + num2).toFixed(2))...

The largest representable number in JavaScript is (2^53) - 1, or, written out, 9007199254740991. The number you have, 9223372036854775808, is more than 1024 times that quantity. If you want to work with numbers larger than the one above, you should use a big integer library. JavaScript does not have one...

Simple for loop across the range you defined: puts "Enter first number: " first = gets.to_i puts "Enter second number: " second = gets.to_i total = 0 for i in (first..second) do total += i end puts total Note that if you don't enter a valid number, it will converted...

php,arrays,string,pagination,numbers

Haven't tested it, but I think this could give you an idea. This doesnt work for numbers >= 10. function get_near_elems($number = 5) { $pages = "1,2,3,4,5,6"; $x = strpos($pages, $number); if($x == 0) return array('prev' => null, 'next' => $pages[$x]); else if($x == (strlen($pages) - 1)) return array('prev' =>...

It looks like you're trying to determine whether an object's location (its center point) falls within a rectangular area. Try using the is within operator: if the loc of image "yellowdisk.png" is within the rect of graphic "targetRect" then # do true stuff else # do false stuff end if...

php,floating-point,numbers,integer

It is pretty simple. modulo (%) is the operator you want, it determines if there would be a remainder if x is divided by y... for example (3 % 2 = 1) and (4 % 2 = 0). This has been asked before too - pretty common question - you...

You could try the below negative lookarounds based regex. (?<!\d)\d(?!\d) DEMO OR This would work if you're running javascript. Pick the number you want from group index 1. Lookarounds are assertion which won't consume any character. (?:^|\D)(\d)(?=\D|$) DEMO...

string,numbers,ocaml,typeconverting

Basically, a more correct way would be to convert strings to numbers, and the apply operations, and afterwards inject the values back into the string, e.g, let sum x y = string_of_int (int_of_string x + int_of_string y) If you want to perform your arithmetic operations in the field of real...

Calculate the prime factorization of the LCM, then multiply all those primes together mod 10^9+7: long modulus = 1000000007 long product = 1; for (long prime : primes) { product = (product * prime) % modulus; } ...

Try this: var isSquare = function (n) { return n > 0 && Math.sqrt(n) % 1 === 0; }; Check if number is positive Check if sqrt is complete number i.e. integer Demo...

osx,numbers,automator,iwork,jxa

This AppleScript: tell application "Numbers" tell table 1 of sheet 1 of document 1 set selection range to range "A2:A20" end tell end tell is actually setting the table's selection range to the table's range named "A2:A20". Here is the equivalent JavaScript: var Numbers = Application("Numbers") var table = Numbers.documents[0].sheets[0].tables[0]...

Your first problem is your while anumber > j:, at no point does j get incremented so you have an infinite loop. Next the pseudo code has no need of modulo (%) as it is a prime sieve. A prime sieve removes all numbers which can't be prime; in the...

You can use System.Collections.BitArray for this task, it allows you to convert a number to a bit array, then manipulate individual bits of this number, then convert it back. Here's how you could insert a bit into a number at a certain position: public static byte insertIntoPosition(byte number, int position,...

1 is not prime, so if you pass 1 to the function it will return 1 as the max prime factor which is incorrect. Perhaps a check returning a value like NaN or undefined may be helpful to prevent invalid values, this depends on if you need to limit the...

javascript,numbers,int,square,digit

function sq(n){ var nos = (n + '').split(''); var res=""; for(i in nos){ res+= parseInt(nos[i]) * parseInt(nos[i]); } return parseInt(res); } var result = sq(21); alert(result) ...

You can seed a random number generator, so it will always produce the same random sequence: Random rnd = new Random(1/* Any seed value you want in here */); If you want to force some repeating numbers, you could so something like this: static int[] RandomIntArray() { Random rnd =...

Note that \luaexec (requires \usepackage{luacode}) is not expandable, so it cannot be used in places where (Lua)TeX expects a <number> after expansion. \documentclass{article} \usepackage{luacode} \usepackage{ifthen} \begin{document} \newcommand\testC{123} \ifthenelse{\testC<0}{negative}{positive} % works fine ! \newcommand{\testD}{\directlua{tex.sprint("123")}} % write to avoid the print carriage return - p$ \testD % prompt 132 just as \testC...

javascript,object,null,numbers

Your error occurs because you return 0 to the filter function which evaluates that as falsey. var arr = [0,1,2,3]; console.log(arr.filter(function(v) { return v; })); ...

javascript,jquery,numbers,format

Looking through the docs, .number(true, ...) is described as such the 'true' signals we should read and replace the text It looks like the first parameter of number() can also be a number itself. So when evaluating the number of <span format='float'>-50</span>, let's just try to pass the elements own...

Maybe safest bet would be to try parse input with both cultures, something like this: private static int ConvertStringValue(string value) { decimal valDouble; var comma = (NumberFormatInfo)CultureInfo.InstalledUICulture.NumberFormat.Clone(); comma.NumberDecimalSeparator = ","; comma.NumberGroupSeparator = "."; var dot = (NumberFormatInfo)CultureInfo.InstalledUICulture.NumberFormat.Clone(); dot.NumberDecimalSeparator = "."; dot.NumberGroupSeparator = "."; if (decimal.TryParse(value, NumberStyles.Currency, comma, out valDouble)) {...

Create a list with the numbers you want to have, and then randomly select an element from this list and remove it. Repeat this until your list is empty, and start over again. This way you will get each number once in n tries, but their order will be random....

python-3.x,dictionary,numbers,key

Python use hash table for storing the dictionaries so there is no ordered in dictionaries or other objects that use hash function. But about the indices of items in a hash object, python calculate the indices based on following code within hashtable.c: key_hash = ht->hash_func(key); index = key_hash & (ht->num_buckets...

Try this: string Input = "919982115672"; Console.Write(Search(Input)); public string Search(string Input) { Dictionary<string, string> PreDefinedSearchAndTexts = new Dictionary<string, string>(); PreDefinedSearchAndTexts.Add("8211", "Hello"); PreDefinedSearchAndTexts.Add("82", "My name is inigo montya"); PreDefinedSearchAndTexts.Add("9821", "You killed my father"); PreDefinedSearchAndTexts.Add("5672", "Prepare to die"); StringBuilder sb = new StringBuilder(); foreach(string Key in PreDefinedSearchAndTexts.Keys) {...

regex,string,oracle,oracle11g,numbers

ok I'm not exactly clear on what you are doing however maybe the following might help. creating a table from data create table mytable as select 'NL 4633 4809 KTU' txt from dual; you can use regex to split the words up into columns SELECT REGEXP_SUBSTR (txt, '[^ ]+', 1,...

php,algorithm,numbers,combinations,letter

This should work for you: Basically I have an array with all letters ([A-Z]) and an array with all numbers ([0-9]). Then you define which order of possible characters you want. E.g. here you want letterNumber, letterNumber and then the third spot only number. After this you loop through everything...

text,import,numbers,powerquery

Power Query adds an automatic type conversion step after certain data sources like CSV. If you look at the Applied Steps list you'll see that the last step is one that changes the type. You can delete that step to undo the type change. You can also edit the step...

It was NaN because you did not initialize result at the start. Let us see the script: var result = 0; var x; for (var i = 0; i<100; i++) { x = i ^ i result = x + result; } Here you are running the bitwise XOR for...

There's a bug in your condition -- you should be checking whether either the row or column was wrong, not whether both are wrong. As it is, if only one of the numbers is wrong, your program says you win -- so there are a whole lot of inputs that...

numbers,hex,decimal,autoit,definition

As per AutoIt documentation - Language Reference - Datatypes: In AutoIt there is only one datatype called a Variant. A variant can contain numeric or string data and decides how to use the data depending on the situation it is being used in. Issuing ConsoleWrite(0x00200000 & @LF) demonstrates stated behavior....

r,numbers,decimal,decimalformat

The commenters are right. It doesn't matter how long the list of numbers is. R can do the operation in one go. x <- c(25.01, 25.8, 25.4) x-15 [1] 10.01 10.80 10.40 If you do run into a situation with many wide-ranging numbers and need to literally keep what comes...

You could do it like this: List<String> matches = new ArrayList<String>(); Matcher m = Pattern.compile("[0-9]+").matcher("good_mor9ni13ng_23guys"); while (m.find()) { matches.add(m.group()); } ...

java,android,android-edittext,numbers,android-inputtype

I managed to do it with a custom class extending EditText that adds a TextWatcher in the constructor. In the afterTextChanged method it tries to convert that to a long. If it fails (NumberFormatException) it sets the number to the respective min / max value (based on the "-" sign...

Your problem is, that you always end up with a float value in your variable $hex. And the function mt_srand() as you can also see in the manual: void mt_srand ([ int $seed ] ) Expects an integer. So what it does is, it simply tries to convert your float...

java,android,numbers,transition

Hope this little demo using a ValueAnimator will inspire you to find an appropriate solution. You can specify the duration of the animation (see code) and even adjust the frame-rate by saying mAnimator.setFrameDelay(frameDelay);. By using animator.isRunning() or animator.isStarted() you can prevent double-click malfunction or other unwanted behaviour while the current...

but as for this method, I don't understand the purpose of Integer.MAX_VALUE and Integer.MIN_VALUE. By starting out with smallest set to Integer.MAX_VALUE and largest set to Integer.MIN_VALUE, they don't have to worry later about the special case where smallest and largest don't have a value yet. If the data...

Do it recursive for +1 elegance function zeroPad (str) { str = str + ''; // cast to string. if (str.length > 5){ return str; } return zeroPad('0' + str); }; Call it like this zeroPad(14); // '000014' ...

Try this: var num = 1234 var first = num/100 var last = num%100 The playground's output is what you need. ...

math,count,language-agnostic,numbers,sequence

So first you want all numbers with the digits 0 in order. i.e. just 00 Then all numbers with the digits 0,1: 00, 01, 10, 11 but excluding 00 Then all numbers with digits 0,1,2: 00, 01, 02, 10, 11, 12, 20, 21, 22 but excluding 00, 01, 10, 11...

android,string,exception,numbers,operator-keyword

You have to use x+1 in your substring, to cut the operator sign from the numerical value: Integer.valueOf(s.substring(x+1, s.length() - 1));...

javascript,jquery,numbers,roundup

The problem isn't just with decimals, you will get the wrong formatting also by entering non digits, e.g., clicking King Kong will result in Kin,g K,ong. So, what you probably want is to filter out non-digits, which can be done by changing the line var oNum= $(this).val(); to: var oNum=...

Change 99999 to 90000 and be careful with brackets. Math.floor(Math.random()*90000) + 10000; ...

javascript,html5,validation,input,numbers

just use a regular expression like this textboxText= textboxText.replace(/^0+/, '') ...

vb.net,visual-studio-2010,random,numbers,64bit

Signed Integer data types only go to 32 bits Unsigned Integer data types only got to 32 bits For 64 bits of data you should use LONG or ULONG The reason the integer OVERFLOWS is because the data type is not large enough to hold your 64 bits of data!...

user current timestamp in place of $count, it will always keep increasing. $name .= time() ...

This is a prime example for a some kind of joint-typeclass. Start by defining a thing just like Numeric[T], but for addability: trait Addable[T, S] { type Result def add(x: T, y: S): Result } Now, define your add function: def add[T,S](op1: T, op2: S)(implicit op: Addable[T, S]): op.Result =...

Because small floating point numbers are normally displayed using exponential notation, so 0.00001 is converted to 1.0E-5, which doesn't match the regexp. You can see this if you simply do: echo 0.00001; Regular expressions should be used with strings, not numbers. preg_match('/^[0-9]{1,10}(\.[0-9]{1,9})?$/', '0.00001'); ...

javascript,node.js,numbers,parseint

I think the reason is parseInt converts the passed value to string by calling toString which will return "-3.67394039744206e-15", then parses it so it will consider -3 and will return it. The mdn documentation The parseInt function converts its first argument to a string, parses it, and returns an integer...

The problem is overflow. 5e9 is 5'000'000'000, but the largest number a 32-bit signed integer (long on 32-bit platforms, and on 64-bit Windows; it's 64-bit on 64-bit Linux) can hold is 2'147'483'648.

Use this: It should work echo preg_replace('/\: *([0-9]+\.?[0-9e+\-]*)/', ':"\\1"', $jsonString); ...

Regex could be a solution since your numbers seem to be declared as strings. Code : <?php $re = "/(\d\.\d{2})(?!\d)/"; $array_input = array('1.00', '1', '1.000'); foreach($array_input as $row) { if(preg_match($re, $row, $matches) == 0) echo $row . " isn't a valid value with 2 decimals only. <br>"; else echo $row...

sql-server,insert,numbers,comma

Commas delimit values. By using commas, you are telling SQL Server to expect more columns of data. SQL Server is not white space sensitive, so white space is not used as a delimiter.

numbers,character,formula,powerquery

There are likely several ways to do this. Here's one way: Create a query Letters: let Source = { "a" .. "z" } & { "A" .. "Z" } in Source Create a query GetFirstLetterIndex: let Source = (text) => let // For each letter find out where it shows...

There are quite few mistakes, see this: $Account = "opr" $Accountnum = 1000 do { $Accountname = $Account + $Accountnum; $query = "(&(objectClass=user)(samaccountname=$Accountname))" $result = ([adsisearcher]$query).FindOne() if($result -eq $false) { break } $Accountnum++ } while($true) ...

java,generics,numbers,autoboxing

Well, how about : public static <T extends Number> T firstNonZero(T... values) { T zero = null; for (T value : values) { if (value.doubleValue() != 0.0) { return value; } else { zero = value; } } return zero; } This is assuming at least one value is passed...

php,loops,random,while-loop,numbers

This should work for you: No need for a loop. Just first fill an array with 1's $many times. Then array_merge() the array with the 0's which you fill up until $length elements. At the end just shuffle() the array and implode() it to print it <?php $min = 0;...

php,json,parsing,numbers,bigint

As long as your PHP version can actually handle large integers, meaning if you're running a 64-bit version of PHP (on something other than Windows), json_decode has no problem with it: $json = '{"foo":9223372036854775807}'; $obj = json_decode($json); $json2 = json_encode($obj); var_dump(PHP_INT_MAX, $obj, $json2); int(9223372036854775807) object(stdClass)#1 (1) { ["foo"]=> int(9223372036854775807) }...

javascript,numbers,syntax-error

The expressions 0.0 and 00.0 are parsed differently. 0.0 is parsed as a numeric literal 1 00.0 is parsed as: 00 – octal numeric literal 2 . – property accessor 0 – identifier name Your code throws syntax error because 0 is not a valid JavaScript identifier. The following example...

This is a perfect case for using regular expressions. Regular expressions are powerful tools that seek patterns in text. In your case, what you'd want to find first are the numbers that begin the string. Next, you want to find the corresponding numbers at the end of the string. You...

You could do something like this: function decimal($number){ $num = explode('.', $number); return $num[1]; } $decimal = decimal(10.5); echo $decimal; // should be 5 ...

You should specify the sig figs and they will display properly. $lat = "20.6350"; $lng = "-103.5334"; print number_format($lat, 4); // 4 sig figs print number_format($lng, 4); See http://php.net/number_format for additional formatting info UPDATE Based on your comments above, seems the string you're pulling varies in length, correct? Why not...

php,arrays,sorting,object,numbers

The function usort returns "true" on success. So, good news :). If you want to check if the sort is done, you only have to check your $all_studies object after the usort. $status = usort($all_studies, "sort_objects_by_graduationyear"); print_r($all_studies); ...

number_to_human is very close to what you're asking for. It rounds up and down, so 410589 would become "411 K", not sure if that's ok. You'll need either some I18n mappings, or provide a hash of units to get your suffixes, and a little tweaking to get the precision you...

file,variables,batch-file,numbers,numeric

You can create and use environment variables with names that begin with a digit, but it is not a good idea, and should be avoided. Defining the variable is no problem. But expansion using normal percent expansion is a problem. The problem is the batch parser sees the inital %1...

Use std::istringstream. Here is an example: #include <sstream> #include <string> #include <fstream> #include <iostream> using namespace std; int main() { string line; istringstream strm; int num; ifstream ifs("YourData"); while (getline(ifs, line)) { istringstream strm(line); while ( strm >> num ) cout << num << " "; cout << "\n"; }...