JavaScript Number preserve leading 0 - javascript

I have a problem, I build a very simple javascript search for postal codes.
I am using JS Numbers because I want to check if the passed number (search term) is less||equal or more||equal to the max and min.
value >= splitZips[0] && value <= splitZips[1]
But the Javascript Number var type deletes leading 0, which is a problem because I have postal codes like 01075 and also postal codes like 8430. So it can not find the small 4 digit codes.
Any idea how to fix this?

Represent them as a String. Outside of strict mode, a leading zero denotes an octal number otherwise.
Also, why would a leading zero have any significance when calculating numbers? Just use parseInt(num, 10) if you need to.

Store and display the postcodes as strings, thus retaining the leading zeros. If you need to make a numerical comparison convert to number at the time. The easiest way to convert is with the unary plus operator:
var strPC = "01745",
numPC = +strPC;
alert(numPC === +"01745"); // true
+value >= +splitZips[0] && +value <= +splitZips[1];
// etc.
Before you start comparing you might want to ensure the entered value actually is numeric - an easy way to be sure it is a four or five digit code with or without leading zeros is with a regex:
/^\d{4,5}$/.test(searchTerm) // returns true or false

Instead a parseInt you could use type casting :)
"0123">"122" // false
+"0123">"122" // true | that means: 123>"122"
Btw, what more you can use a each of bitwise operators :
~~"0123"
"0123"|0
"0123"&"0123"
"0123">>0
"0123"<<0
With the same effect :)

Related

Why is parseFloat('1/2') == 1 in Javascript

I am unable to understand this:
parseFloat('1/2') == 1 Not Expected
parseFloat(1/2) == 0.5 Expected
parseFloat('0.5') == 0.5 Expected
parseFloat(0.5) == 0.5 Expected
Is it some issue or am I doing something wrong? Also, how to get
parseFloat('1/2') == 0.5
As in doc mentioned parseFloat
parseFloat parses its argument, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.
so 1/2 treated as a string.
Not only that - this string does not contain a valid number representation in JavaScript.
Numbers in JavaScript may include -, 0-9, . and +e.
/ is not a part of it. Therefore - parseFloat parses all the characters that are legal as a number - which in your case is just the 1 part, and ignores rest.
1/2 in JavaScript is not a number, but an expression including 2 numbers and an operator (1 = num, / = operator, 2 = number). What can execute expressions?
You can use eval to calculate fractional form.
console.log(eval('2/3'))
Mind that eval is a dangerous function: using eval on user-input can lead to exploits.
parseFloat does not understand the / character as a division nor does it do an eval of the string input.
It simply stops looking when it encounters the character it doesn't understand and returns the correctly parsed first part:
console.log(
parseFloat("1/2"), // 1
parseFloat("3/2"), // 3
parseFloat("1kahsdjfjhksd2") // 1
)
If you do want to evaluate the string "1/2" to the number 0.5, you can use eval. Be careful, because using eval can be a security risk, slow and hard to debug.
console.log(
eval("1/2")
);
Not 100% sure. but if you play around with parseFloat a bit you will see that it tries to convert every number it finds to a float, but stops as soon as there is a unexpected value so :
parseFloat('1/asdf') == 1
but
parseFloat('0.5') == 0.5
So parse float does not calculate for you, but just parses every number it finds, until there is something non numerical.
Your parsing a string that will be converted to 1. If your string was only numbers (e.g. "0.5") them they would be converted correctly, but as it includes the '/', the automatic type conversion will not occur and it will remain as a string. When using numbers the expected behavior occurs, that is:
parseFloat(1/2) === 0.5 // true

regular expression not validating 4 value types of numbers correctly

I'm trying to validate a value and that value cannot have a zero and then a number in front of it in my expression, the expression I have currently selects all the data types of values including the first one which is not what I want can someone help me please.
05lb incorrect
0.2lb correct
1.2lb correct
2lb correct
/(0?[0-9]|\d+)(?:\.\d\lb|\lb)/
You could provide your condition (value cannot have a zero and then a number in front) on regex by using a negative lookahead assertion.
^(?!0\d)\d+(?:\.\d+)?lb$
^(?!0\d) asserts that the there isn't a 0 and a digit present at the start.
DEMO
> /^(?!0\d)\d+(?:\.\d+)?lb$/.test('05lb')
false
> /^(?!0\d)\d+(?:\.\d+)?lb$/.test('0.2lb')
true
> /^(?!0\d)\d+(?:\.\d+)?lb$/.test('1.2lb')
true
> /^(?!0\d)\d+(?:\.\d+)?lb$/.test('2lb')
true
some points are not completely clear (i.e.: always lb at the end? max 1 digit after point? numbers as 1.lb are allowed?), but you can try this:
/^(?:0|[1-9]\d*)(?:\.\d)?lb$/

Is there a way to distinguish integers from very near decimals in Javascript?

Look at those evaluations (actual dump from node 0.10.33)
> parseFloat(2.1e-17) === parseInt(2.1e-17)
false
> parseFloat(2.1e-17 + 2) === parseInt(2.1e-17 + 2)
true
> parseFloat(2.000000000000000000000000000000000009) === parseInt(2.00000000000000000000000000000000000009)
true
How can I tell integers from decimals very near to integers?
It seems that JS (or at least V8) doesn't care about digits smaller than 10^-16 when doing calculations, even if the 64bit representation used by the language (reference) should handle it.
Your examples are pretty much straight forward to explain. First thing to note is, that parseInt() and parseFloat() take a string as an input. So you inputs first get converted to string, before actually getting parsed.
The first is easy to see:
> parseFloat(2.1e-17) === parseInt(2.1e-17)
false
// look at the result of each side
parseFloat(2.1e-17) == 2.1e-17
parseInt(2.1e-17) == 2
When parsing the string "2.1e-17" as integer, the parse will stop at the dot as that is no valid digit and return everything it found until then, which is just 2.
> parseFloat(2.1e-17 + 2) === parseInt(2.1e-17 + 2)
true
// look at the result of each side
parseFloat(2.1e-17 + 2) == 2
parseInt(2.1e-17 + 2) == 2
Here the formula in the parameter will be evaluated first. Due to the limitations of floating point math (we just have 52bit for the mantissa and can't represent something like 2.000000000000000021), this will result in just 2. So both parseX() function get the same integer parameter, which will result in the same parsed number.
> parseFloat(2.000000000000000000000000000000000009) === parseInt(2.00000000000000000000000000000000000009)
true
Same argument as for the second case. The only difference is, that instead of a formula, that gets evaluated, this time it is the JavaScript parser, which converts your numbers just to 2.
So to sum up: From JavaScript's point of view, your numbers are just the same. If you need more precision, you will have to use some library for arbitrary precision.
This is something I learned from ReSharper
instead of using expressions like
if (2.00001 == 2) {}
try
if (Math.abs(2.00001 - 2) < tolerance) {}
where tolerance should be an aceptable value for you for example .001
so all values wich difference is less than .001 will be equals
Do you really need 10^-16 precision I mean that is why 1000 meter = 1 kilometer, just change the unit of the output so you dont have to work with all those decimals

Need a Reg Expression to find a decimal range

I am currently needing a reg expression which will evaluate a decimal range.
The requirements are as below
1) Can allow only 1 or 2 decimal places after dot or can as well allow whole numbers (e.g) 1234 , 123.4, 1245.78 are valid
2) The range should be within 9999 (e.g) 9999.0 , 9998.99 , 9999.00 - Valid | 9999.01,10000.00 - not Valid
3)Do not require leading or trailing zeros
So far i have tried to achieve till writing this reg expression
/^[0-9]\d{1,4}(\.\d{1,2})?$/.test(value);
... but unable to proceed with setting range till digit 9999 (since 9999.01 also not valid )can you help.
Why don't just apply regular expression to determine is your string a valid digit with dots float, then typecast it to Number and find wether it is bigger than 9999 or not.
Regexp for your needs caould be very complex and take too much CPU from client.
Here's something quick and dirty that should work for you: http://regex101.com/r/vK1jM3
/^(?(?=9999)9999(?:\.0+)?|\d{1,4}(?:\.\d{1,2})?)$/gm
I merely handle the special case of 9999
This works as far as I can see:
^(9999(?!\.[1-9])(?!\.0[1-9])\.[0-9]{1,2}|9999|(?!9999)[0-9]{1,4}|(?!9999)[0-9]{1,4}\.[0-9]{1,2})$
Testing it out:
var monstrosity = /^(9999(?!\.[1-9])(?!\.0[1-9])\.[0-9]{1,2}|9999|(?!9999)[0-9]{1,4}|(?!9999)[0-9]{1,4}\.[0-9]{1,2})$/;
console.log(monstrosity.test("9999.00")); // true
console.log(monstrosity.test("9999.01")); // false
console.log(monstrosity.test("9999")); // true
console.log(monstrosity.test("9998.4")); // true
console.log(monstrosity.test("0")); // true
console.log(monstrosity.test("0.5")); // true
If you add something like this to the codebase, future maintenance programmers will hunt you down with pitchforks. Try to solve the range check without regex, as webbandit suggested.
Why a regexp? Just do
x > 0 && x <= 9999 && (x*100 - Math.floor(x*100) == 0)

Regex to match from 0.0 to 150.0 (including floating point)

I have a problem: i should match values from 0.0 to a specific double value (for example, i should match from 0.0 to 150.00 including value as 12, 21.23213, 149.111)
anyone can help me?
i tried everything.
i used this regexp for match by 0.0 to 60.0 but it doesn't work
(^0(\.[0-9]+)?$|^[1-9]{1}(\.[0-9]+)?$|^[1-5]{1}[0-9]{1}(\.[0-9]+)?$|^60$)
with 123 it doesn't work
thank you in advance
Marco
Don't use a regex - use Number, check it's a number with isNaN, then compare values using <= and >=.
e.g.
var your_val = "3.05";
var your_val_num = Number(your_val);
if (!isNaN(your_val_num) && your_val_num >= 0 && your_val_num <= 150) {
// do something
}
N.B. I've changed my answer to use Number rather than parseFloat, per AndyE's comment, and to check for NaN before doing numerical comparisons, per lincolnk's comment.
I agree with the other answers: regex is a poor way to do numeric comparisons.
If you really have to, either:
because a dumb framework you're stuck with only allows regex checks, or
you need extra decimal precision that a JavaScript Number can't provide (as JavaScript has no built-in Decimal type)... this won't be the case for comparing against the whole numbers 0 and 150 though
then:
^0*( // leading zeroes
150(\.0+)?| // either exactly 150
1[0-4]\d(\.\d+)?| // or 100-149.9*
\d{0,2}(\.\d+)? // or 0-99.9*
)$
(newlines/comments added for readability, remove to use.)
This doesn't support E-notation (150=1.5E2) but should otherwise allow what normal JS Number parsing would.
forget regex - just check if(parseFloat(x)=<150 && parseFloat(x)>=0)

Categories

Resources