Regular expression with decimal point - regex

I am trying to validate a textbox with a regular expression...
regex expression=(\d{0,4})?([\.]{1})?(\d{0,2})
I am having a problem with the decimal point. the decimal point is optional. the regex should validate for only one decimal point.
example 1.00 ,23.22 , .65 is valid
1.. or 23.. is invalid.
Any suggestions for improving my regex??

Try this one : ^\d{1,4}(\.\d{1,2})?$
It should match :
1
200
9999
12.35
522.4
But not :
1000000
65.
.65
10.326
65..12
Edit :
If you want to match 65. or 9999. use this one instead (see comments) :
^\d{1,4}(\.(\d{1,2})?)?$

Use Application Logic Instead
While you could certainly construct a regular expression for this, it seems simpler to check for a data type or class, or simply scan your input for decimals and then count them. For example, using Ruby:
Check that value is a float or integer.
# Literal value is a float, so it belongs to the Float class.
value = 1.00
value.class == Fixnum or value.class == Float
=> true
# Literal value is an integer, so it belongs to the Fixnum class.
value = 23
value.class == Fixnum or value.class == Float
=> true
Count decimals and make sure there's no more than one.
# Literal value is a float. When cast as a string and scanned,
# only one decimal should be found.
value = 23.22
value.to_s.scan(/\./).count <= 1
=> true
# The only way this could be an invalid integer or float is if it's a string.
# If you're accepting strings in the first place, just cast all input as a
# string and count the decimals it contains.
value = '1.2.3'
value.to_s.scan(/\./).count <= 1
=> false

Related

In C++ : how to print the digits after the decimal.

In C++ : how to print the digits after the decimal.
For example i have this float number ( 12.54 ), and i want to print it like this ( 0.54 ).
Thank you all.
You can use modf function.
double integral_part;
double fractional = modf(some_double, &integral_part);
You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.
The simplest way
float f = 10.123;
float fract = f - (int)f;
std::cout << fract;
But for large input you can obtain integer overflow. In this case use
float fract = f - truncf(f);
Output
0.123
In C++ : how to print the digits after the decimal. For example i have
this float number ( 12.54 ), and i want to print it like this ( 0.54
).
If you want to use get the fractional part of a floating type number you have a choice of std::floor or std::trunc. Non negative numbers will be treated the same by either but negative numbers will not.
std::floor returns the lowest, non fractional, value while std::trunc returns the non fractional towards 0.
double f=1.23;
floor(f); // yields .23
trunc(1.23); // also yields .23
However
double f=-1.23;
floor(f); // yields -2
trunc(f); // but yields -1
So use trunc to get the fractional part for both positive and negative f's:
double f=-1.23;
f - floor(f); // yields .77
f - trunc(f); // but yields -.23

Represent infinity in the Num module

In the Num module, it is said :
Numbers (type num) are arbitrary-precision rational numbers, plus the special elements 1/0 (infinity) and 0/0 (undefined).
I expected to find this infinity but can't find it. I guessed, then, that I could create it by hand :
let infinity = let one = Int 1 and zero = Int 0 in one // zero
But bum :
Exception: Failure "create_ratio infinite or undefined rational number".
So, ok, there is this val infinity : float in Pervasives, let's find a num_from_float. Oh, there's no such function...
Well, does anyone know how to represent positive and negative infinity with Num ?
By default, special numbers are disabled. This behavior can be controlled with the Arith_status module. For example, to allow zero denominators, use the following:
Arith_status.set_error_when_null_denominator false
Once the flag is set, your infinity definition works fine:
let infinity = let one = Int 1 and zero = Int 0 in one // zero;;
val infinity : Num.num = <num 1/0>
float_of_num infinity;;
- : float = infinity

Python code to convert decimal to binary

I need to write a Python script that will convert and number x in base 10 to binary with up to n values after the decimal point. And I can't just use bin(x)! Here's what I have:
def decimal_to_binary(x, n):
x = float(x)
test_str = str(x)
dec_at = test_str.find('.')
#This section will work with numbers in front of the decimal
p=0
binary_equivalent = [0]
c=0
for m in range(0,100):
if 2**m <= int(test_str[0:dec_at]):
c += 1
else:
break
for i in range(c, -1, -1):
if 2**i + p <= (int(test_str[0:dec_at])):
binary_equivalent.append(1)
p = p + 2**i
else:
binary_equivalent.append(0)
binary_equivalent.append('.')
#This section will work with numbers after the decimal
q=0
for j in range(-1, -n-1, -1):
if 2**j + q <= (int(test_str[dec_at+1:])):
binary_equivalent.append(1)
q = q + 2**j
else:
binary_equivalent.append(0)
print float((''.join(map(str, binary_equivalent))))
So say you call the function by decimal_to_binary(123.456, 4) it should convert 123.456 to binary with 4 places after the decimal, yielding 1111011.0111.
The first portion is fine - it will take the numbers in front of the decimal, in this case 123, and convert it to binary, outputting 1111011
However, the second portion, which deals with values after the decimal, is not doing what I think it should. The output it gives is not .0111, but rather .1111
I ran through the code with pen and paper writing down the value for each variable and it should work. But it doesn't. Can anyone help me fix this?
I call the function as decimal_to_binary(123.456, 4) and it prints out 1111011.1111
You're close, but there's an issue with your comparison when you go beyond the decimal:
if 2**j + q <= (int(test_str[dec_at+1:])):
What you're doing here is comparing a fractional value (since j is always negative) to a whole integer value. This comparison will, for all practical purposes, always be true.
Based on the surrounding logic, my guess would be that you're attempting to compare it to the actual decimal value here. Using your data, that would be 0.4 on the first iteration, so you expect the statement to be evaluated as:
0.5 <= 0.4
The actual comparison in your code is:
0.5 <= 4
There are two separate issues here:
You're taking all of the numbers after the decimal point, but not actually including the decimal point itself in your extraction. This is primarily why you are getting whole numbers in your test incorrectly. This is fixed simply by referencing test_str[dec_at:] rather than test_str[dec_at+1:]
You're casting to int. Even if you applied the change in the first point, your code would still not run correctly. However, in that case it would be because the cast would truncate the value down to 0 on every iteration. Cast to a float instead: float(test_str[dec_at:])
Your comparison line thus becomes if 2**j + q <= (float(test_str[dec_at:])):, which provides the correct output on my machine.
Note that floating point comparisons can be "finicky" in some situations, depending on rounding and the like. There are ways to mitigate this if needed.

Print a certain number of digits after decimal point in PRINT statement in FORTRAN

I have a double precision variable x = 10, and when I use the statement: Print(,) x Fortran will print out a lengthy number as 10.0000000000000 . I only want 2 digits after the decimal point (.), that is 10.00 what should I do , instead of using Print(,) ? Thank you all in advance.
X=10
WRITE(*,44) X
44 FORMAT(F4.2)
I think the FORMAT statement is what you're after. The F4.2 says to write a real in 4 columns with 2 digits after the decimal.

Regex for decimal numbers

Could anybody provide a regular expression for a number that has to be between 1 and 17 in length, and could optionally contain a mantissa of up to 4 places? The length of 17 includes both the characteristic and the mantissa.
Edit:
The length of 17 excludes the decimal point.
Valid examples:
12345678901234567
1234567890123.4567
123456789012345.67
12.34
Invalid:
12345678901234.5678 (Length of numerals = 18)
Thanks.
^\d{17}$|^\d{13}(?=.{5}$)\d*\.\d*\d$
Regex explained:
^\d{17}$ //A string of 17 digits
| //or
^\d{13} //13 digits followed by
(?=.{5}$) //5 characters, of which
\d*\.\d* //one is a decimal point and others are digits
\d$ //and the last one is a digit
OK, this is the best I could do:
/^\d{1,17}$|(?=^.{1,18}$)^\d+\.\d{1,4}$/
Basically, match 1-17 digits, or strings of length 1-18 which consist of two sets of digits separated by a period. The right set can only contain between 1-4 digits.
Don't do this completely in regex. The problem becomes nearly trivial in most programming languages, and that way will be easier for you to write, verify, test, and maintain. You can still use regex for part of the solution, of course, but you don't have to. Pseudocode:
m = re.match(r"(?P<before>[0-9]+)(?P<after>\.[0-9]{1,4})?$", input_string)
if not m:
return "no match"
before, after = m.group("before", "after")
after = after[1:] if after else "" # remove period or set to empty string
if len(before) + len(after) > 17:
return "incorrect length"
return "valid"
It's not particularly pretty, but with so few possibilities (0,1,2,3,4 length mantissa) I would probably just list them all:
\d{17}|\d{16}\.\d{1}|\d{15}\.\d{2}|\d{14}\.\d{3}|\d{13}\.\d{4}
in your favourite language, you can do a couple of logical checks, eg Python
num="1234567890133.3456"
if "." in num and len(num)==17 :
n=num.split(".")
if len(n[1])>4:
print "cannot have more than 4 decimal places"
elif len(n)==2 and n[0].isdigit() and n[1].isdigit():
print "yes, decimal"
elif len(num)==17 and num.isdigit():
print "%s is number with no decimal and is exactly 17 digits." % num
else:
print "%s not ok, check length is 17" % num
I have created this regex from above great solutions. may it help any one. Please let me know if you find any bug in it.
String decimalRegex =""+
"^(?!0[\d,])\+?" + // ^ Start of Number
"(\d{0,"+size+"}|" + // Numeric value without group symbol | (OR)
"(\d{0,"+rem(size,groupSize)+"},)?"+
"(\d{0,"+groupSize+"},) {0,"+div(size,groupSize)+"}\d{"+groupSize+"})" + // Numeric value with group symbol
"((([a-zA-Z]{0,2}|\"|\')\s?\+?)|\.)"+
"(\d{0,"+scale+"})?" + // Decimal value without group symbol
"(\s?([a-zA-Z]{0,2}|\"|\'))$"; // Ends with
private int rem(int size,int groupSize ){
int rem = (size - groupSize)%groupSize;
return rem;
}
private int div(int size,int groupSize ){
int div = (size - groupSize)/groupSize;
return div;
}