Horses in the US are typically measured in hands and inches. A hand is basically just 4 inches. So if a horse was say 62 inches. he would be 15.2 hands tall NOT 15.5. This is because the portion to the right of the decimal is really the remaining inches less than 4, a fraction of a whole hand expressed as a decimal.
Or to be more concise, the portion to the right of the decimal point can only be a single digit that is either a 1, a 2 or a 3. The portion on the left should be a positive integer. The measurement could also just be a whole positive integer if, for example the horses measurement in inches was a multiple of 4.
I am pretty much a dummy on RegEx and I was unable to find an example of this on line and my attempts to modify ones that seem close have ended in failure :)
These are examples of matches: 15.1, 9.2, 100.3, 16
These are examples of non-matches: 15.10, 15.01, 19.4, -15.1, 16.0
Oh and one last thing. I will b using this for validation using JavaScript and perhaps C# as well.
The regex is ^[0-9]+(\.[1-3])?$
in js:
var rx = /^[0-9]+(\.[1-3])?$/;
in c#
var rx = new Regex(#"^[0-9]+(\.[1-3])?$");
If you're only able to have an integer or an integer followed by .1, .2 or .3, you could do that with something like:
\d+(\.[123])?
with appropriate \b (or ^/$) boundary markers at the ends, depending on the method you're using to match (whole string or partial).
If you don't want true internationalised digits, you could replace \d+ with something like [1-9][0-9]* instead.
Related
So, there are plenty of questions and answers about standard ways of parsing feet and inches with regex. A casual search led me easily to:
Link1
Link2
But these options are very specific with what they are looking for and are not versatile enough for what I would want an expression to do. Desirably, I wanted a regex to match all ft inches dimensions like those below:
Example matches (12 and 3 and 1/4 are just examples, matches should not be by line (not just $)):
12' 3"
12 feet 3 inches
12 ft 3 in
12 ft. 3 in.
12' -3"
-12 feet 3 inches (Should capture the negatives)
12'- 3" (Should not mistaken as -ve 3, but not necessarily needed to be processed with regex)
12' 3 1/4"
12' 3.25"
12 ft 3 1/4 in.
12' (Need to capture "single" dimensions provided that it is not logically matched to next or prior)
3"
3 1/4 inches
-3.25"
3 1/4feet
Desired non-matches
12' 12'
3inches 12'
3 inches 3 inches (need to match separately = matches 3 inches twice)
3 - 2ft (need to be able to exclude the 3 and only match -2ft)
I started out trying to write something and came up with:
/(-*[\d .]+(\/\d)* *){1}(?:FEET|FT\.*|'|INCH|INCHES|IN\.*|")+(?:[ -]*)/gi
But it's too greedy and would accept 12' 12' as one thing. So I started doing some exclusions like what they did within Link 1 up there, but I couldn't get it such that it will work. I tried this:
(-*[\d .]+(\/\d)* *){1}(?:FEET|FT\.*|'|INCH|INCHES|IN\.*|")+(?:[ -]*)(?!=(-*[\d .]+(\/\d)* *){1}(?:FEET|FT\.*|')+(?:[ -]*)){1,2}
and also
((?<!((-*[\d .]+(\/\d)* *){1}(?:INCH|INCHES|IN\.*|")+)))(-*[\d .]+(\/\d)* *){1}(?:FEET|FT\.*|'|INCH|INCHES|IN\.*|")+(?:[ -]*)(?!=(-*[\d .]+(\/\d)* *){1}(?:FEET|FT\.*|')+(?:[ -]*)){1,2}
and I have tried some other approaches, such as
(([-*\d+ *])+(?:FEET|FT\.*|')+(?:\s*-)*){0,1}((\s*\d+[./]*\d*\s*)+(?:INCH|INCHES|IN\.*|")+(?: )+){0,1}
and it works the way I desired, but it also matches a lot of empty strings.
Maybe I am just not looking hard enough or searching the right terms, but I don't think I came across an old post that has something as versatile as I would have liked. If there has been an answer previously that does exactly what I would like, feel free to point it out for me. Thanks!
I came up with this regex based on the test cases provided:
/(?:-[ \t]*)?((?:\d+(?:\.\d*)?|(?:\d+[ \t]+)?\d+[ \t]*\/[ \t]*\d+)[ \t]*(?:[']|feet|ft\.?)(?:[ \t]*(?:-[ \t]*)?(?:\d+(?:\.\d*)?|(?:\d+[ \t]+)?\d+[ \t]*\/[ \t]*\d+)[ \t]*(?:["]|inch(?:es)?|in\.?))?|(?:(?:\d+(?:\.\d*)?|(?:\d+[ \t]+)?\d+[ \t]*\/[ \t]*\d+)[ \t]*(?:["]|inch(?:es)?|in\.?)))/g
Regex101
Basically, the regex is constructed as such:
(?:-[ \t]*)?: Optional negative sign
(?:\d+(?:\.\d*)?|(?:\d+[ \t]+)?\d+[ \t]*\/[ \t]*\d+): Matches whole number (e.g. 10), real number (e.g. 3.45), or fractional number (e.g. 3 1/4, 10/4). Let us denote this part as <number> so that we can see the bigger picture
<number>[ \t]*(?:[']|feet|ft\.?): Feet part. Number and unit optionally separated by space
<number>[ \t]*(?:["]|inch(?:es)?|in\.?): Inch part. Feet part. Number and unit optionally separated by space
(<feet part>(?:[ \t]*(?:-[ \t]*)?<inch part>)?|(?:<inch part>)): Matches string with feet part and optional inch part (optionally separated by hyphen), or only inch part
The code assumes everything on a single line - if you want to match across lines, replace [ \t] with \s.
The regex will pick up valid substrings in non-matching cases - it only cares what it matches is valid, it doesn't care about the context of the match.
I need a regular expression to allow a person to enter their height in the following format either
5'10 or 5'10" making the quotation marks optional for the inches. There also could be a space between the feet and inches like 5' 10 or 5' 10".
thanks for the help in advance.
You should be able to use /\d+'\s?\d+"?/ that will allow the numbers to be multiple digits long, requires the single quote after the first number, allows an optional space after the single quote and optionally selects the double quote.
The following will ensure that the number of feet is no greater than 9 and that the inches are between 0 and 11.
/^\d' ?(?:\d|1[0-1])"?$/
If you wanted to make sure the person is at least 2 feet tall, for example, you can just replace the initial \d with the appropriate range.
/^[2-9]' ?(?:\d|1[0-1])"?$/
For weight validation, you can do something like the following, which will ensure the user enters 2 or 3 digits followed by "kg", with an optional space in between. This can easily be adapted for "lbs", or the units can simply be omitted, depending on your requirements.
/^\d{2,3} ?kg$/
I think you might benefit from reading up on regular expressions and testing them out for yourself.
I'm developing a 3D space game, which is using alot of math formulas, navigation, ease effects, rotations, huge distances between planets, objects mass, and so on...
My Question is what would be the best way in doing so using math. Should I calculate everything as integers and obtain really large integers(over 20 digits), or use small numbers with decimals.
In my experience, math when using digits with decimals is not accurate, causing strange behavior when using large numbers with decimals.
I would avoid using decimals. They have known issues with precision: http://floating-point-gui.de/
I would recommend using integers, though if you need to work with very large integers I would suggest using a big number or big integer library such as one of these:
http://jsfromhell.com/classes/bignumber
https://silentmatt.com/biginteger/
The downside is you have to use these number objects and their methods rather than the primitive Number type and standard JS operators, but you'll have a lot more flexibility with operating on large numbers.
Edit:
As le_m pointed out, another downside is speed. The library methods won't run as fast as the native operators. You'll have to test for yourself to see if the performance is acceptable.
Use the JavaScript Number Object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
Number.MAX_SAFE_INTEGER
The maximum safe integer in JavaScript (2^53 - 1).
Number.MIN_SAFE_INTEGER
The minimum safe integer in JavaScript (-(253 - 1)).
var biggestInt = 9007199254740992;
var smallestInt = -9007199254740992;
var biggestNum = Number.MAX_VALUE;
var smallestNum = Number.MIN_VALUE;
var infiniteNum = Number.POSITIVE_INFINITY;
var negInfiniteNum = Number.NEGATIVE_INFINITY;
var notANum = Number.NaN;
console.log(biggestInt); // http://www.miniwebtool.com/scientific-notation-to-decimal-converter/?a=1.79769313&b=308
console.log(smallestInt); // http://www.miniwebtool.com/scientific-notation-to-decimal-converter/?a=5&b=-32
console.log(biggestNum);
console.log(smallestNum);
console.log(infiniteNum);
console.log(negInfiniteNum);
console.log(notANum);
debugger;
I can only imagine that this is a sign of a bigger problem with your application complicating something that could be very simple.
Please read numerical literals
http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.3
Once the exact MV for a numeric literal has been determined, it is
then rounded to a value of the Number type. If the MV is 0, then the
rounded value is +0; otherwise, the rounded value must be the Number
value for the MV (as specified in 8.5), unless the literal is a
DecimalLiteral and the literal has more than 20 significant digits, in
which case the Number value may be either the Number value for the MV
of a literal produced by replacing each significant digit after the
20th with a 0 digit or the Number value for the MV of a literal
produced by replacing each significant digit after the 20th with a 0
digit and then incrementing the literal at the 20th significant digit
position. A digit is significant if it is not part of an ExponentPart
and
it is not 0;
or there is a nonzero digit to its left and there is a nonzero digit, not in the ExponentPart, to its right.
Clarification
I should add that the Number Object wrapper supposedly offers precision to 100 (Going above this number will give you a RangeType error) significant digits in some browsers, however most environments currently only implement the precision to the required 21 significant digits.
Reading through OPs original question, I believe skyline provided the best answer by recommending a library which offers well over 100 significant digits (some of the tests that I got to pass were using 250 significant digits). In reality, it would be interesting to see someone revive one of those projects again.
The distance from our Sun to Alpha Centauri is 4.153×1018 cm. You can represent this value well with the Number datatype which stores values up to 1.7977×10308 with about 17 significant figures.
However, what if you want to model a spaceship stationed at Alpha Centauri?
Due to the limited precision of Number, you can either store the value 4153000000000000000 or 4153000000000000500, but nothing in between. This means that you would have a maximal spacial resolution of 500 cm at Alpha Centauri. Your spaceship would look really clunky.
Could we use another datatype than Number? Of course you could use a library such as BigNumber.js which provides support for nearly unlimited precision. You can park your spaceship one milimeter next to the hot core of Alpha Centauri without (numerical) issues:
pos_acentauri = new BigNumber(4153000000000000000);
pos_spaceship = pos_acentauri.add(0.1); // one milimeter from Alpha Centauri
console.log(pos_spaceship); // 4153000000000000000.1
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/2.3.0/bignumber.min.js"></script>
However, not only would the captain of that ship burn to death, but your 3D engine would be slow as hell, too. That is because Number allows for really fast arithmetic computations in constant time, whereas e. g. the BigNumber addition computation time grows with the size of the stored value.
Solution: Use Number for your 3D engine. You could use different local coordinate systems, e. g. one for Alpha Centauri and one for our solar system. Only use BigNumber for things like the HUD, game stats and so on.
The problem with BigNumber is with
Precision loss from using numeric literals with more than 15
significant digits
My solution would be a combination of BigNumber and web3.js:
var web3 = new Web3();
let one = new BigNumber("1234567890121234567890123456789012345");
let two = new BigNumber("1000000000000000000");
let three = new BigNumber("1000000000000000000");
const minus = two.times(three).minus(one);
const plus = one.plus(two.times(three));
const compare = minus.comparedTo(plus);
const results = {
minus: web3.toBigNumber(minus).toString(10),
plus: web3.toBigNumber(plus).toString(10),
compare
}
console.log(results); // {minus: "-234567890121234567890123456789012345", plus: "2234567890121234567890123456789012345", compare: -1}
Let N(x) be the value of the decimal numeral with the fewest significant digits
such that x is the double value nearest the value of the numeral.
Given double values a and b, how can we compute the double value nearest N(b)-N(a)?
E.g.:
If a and b are the double values nearest .2 and .3,
the desired result is the double value nearest .1,
0.1000000000000000055511151231257827021181583404541015625,
rather than than the result of directly subtracting a and b,
0.09999999999999997779553950749686919152736663818359375.
As a baseline: In Java, the Double.toString() provides the N(x) function described in the question, returning its value as a numeral. One could take the strings for a and b, subtract them with the elementary-school method, and convert the resulting string to double.
This demonstrates solving the problem is quite feasible using existing library routines. This leaves the task of improving the solution. I suggest exploring:
Is there a function D(x) that returns the number of significant digits after the decimal place for the numeral described in N(x)? If so, can we multiply a and b by a power of ten determined by D(a) and D(b), round as necessary to produce the correct integer results (for situations where they are representable as double values), subtract them, and divide by the power of ten?
Can we establish criteria for which b-a or some simple expression can be quickly rounded to something near a decimal numeral, bypassing the code that would be necessary for harder cases? E.g., could we prove that for numbers within a certain range, (round(10000*b)-round(10000*a))/10000 always produces the desired result?
You can convert to 'integers' by multiplying then dividing by a power of ten:
(10*.3 - 10*.2)/10 == 0.1000000000000000055511151231257827021181583404541015625
It may be possible to work out the appropriate power of ten from the string representation of the number. #PatriciaShanahan suggests looking for repeated 0's or 9's.
Consider using a BigDecimal library such as javascript-bignum instead.
You could also inquire in Smalltalk Pharo 2.0 where your request translates:
^(b asMinimalDecimalFraction - a asMinimalDecimalFraction) asFloat
Code could be found as attachment to issue 4957 at code.google.com/p/pharo/issues - alas, dead link, and the new bugtracker requires a login...
https://pharo.fogbugz.com/f/cases/5000/Let-asScaledDecimal-use-the-right-number-of-decimals
source code is also on github, currently:
https://github.com/pharo-project/pharo-core/blob/6.0/Kernel.package/Float.class/instance/printing/asMinimalDecimalFraction.st
The algorithm is based on:
Robert G. Burger and R. Kent Dybvig
Printing Floating Point Numbers Quickly and Accurately
ACM SIGPLAN 1996 Conference on Programming Language Design and Implementation
June 1996.
http://www.cs.indiana.edu/~dyb/pubs/FP-Printing-PLDI96.pdf
I am looking to create a regular expression in javascript that does the following:
Allows for 1 or more numbers
Then has an optional period (".")
Then has an optional number of digits up to 6
The context is that i need people to enter in numeric values in the millions and i want them to at least include a 0 if they are entering thousands... so they could enter the following:
1 (would be one million)
0.725 (would be 725k)
10.5 (would be 10M 500K)
I also need to ensure that the value doesn't reach over 725.00 (or 725 million).
Thanks in advance.
That sounds like:
/^(?!\d{4})(?![89]\d\d)(?!7[3-9]\d)(?!72[6-9])(?!725\.0*[1-9])(0|[1-9]\d*)(\.\d{1,6})$/
which means:
doesn't start with four digits (i.e., is less than 1000)
doesn't start with 8 or 9 followed by two digits (i.e., is less than 800)
doesn't start with 73-79 followed by a digit (i.e., is less than 730)
doesn't start with 726-729 (i.e., is less than 726)
doesn't start with 725. followed by zero or more zeroes followed by a nonzero digit (i.e., is less than or equal to 725.00).
starts either with 0, or with 1-9 followed by zero or more digits
after that, optionally a decimal point followed by between one and six digits
That said, I'd actually recommend implementing the above as several separate checks, rather than cramming it all into one regex like the above. In particular, the "is less than or equal to 725.00" check is probably better implemented using numeric comparison; and even if you do want to use a regex for that, you probably want to detect it as a separate error from 0.1asefawe so you can give a more precise error-message.
So basically you want a number that would be multiplied by 10^6 to get the true value.
This sounds like a two-stepper; First, verify that the input string is in a format you expect (you can use a regex for this very easily). Then, parse the string into a number variable and test the actual value. The regex pattern for that would look like "[0-9]{1,3}(\.[0-9]{1,6})?", basically matching a number with up to 3 whole digits and 6 fractional digits, the decimal place and fractional digits being optional. If it matches this pattern, then it's parsable into a number, and you can then perform a quick check that your number <= 725.
I honestly don't think it's feasible to create a single Regex that can validate a proper numeric format AND an inclusive maximum range, but here's a start:
"^(725(\.0{1,6})|(([7][2][0-4]|[7][0-1][0-9]|[1-6][0-9]{2}|[1-9][0-9]|[0-9])(\.[0-9]{1,6})?)$"
This will allow any natural whole number from zero to 724, with any fractional part up to six digits from ".000001" to ".999999". It does this in stages; it will match 720-724, or 700-719, or any three-digit number up to 699, or any two-digit number, or any one-digit number. Then, it will also match the quantity "725" explicitly, with an optional decimal point and up to 6 zeroes.
EDIT: While your comment states that you used this pattern, and it does produce the correct result, I had intended it as a "what not to do"; this pattern will be far more costly to evaluate than the first solution, just to avoid a server-side rule check. And you will have to perform a server-side validation anyway; anything done within the confines of the user's browser should be suspect because the user can disable JavaScript or can even use browser plug-ins like FireBug to make your HTML page behave the way he wants, instead of the way you designed it.