Regex and decimal.TryParse are not working to test for decimals - parsing

It is late. I am a beginner with C# and have been to six different websites and cannot find the answer to this question. I am trying to test for decimals to make sure the user enters one and not some other character. All of the solutions out there involve string and decimal. How do I just test for decimal. I am not converting a string to a decimal. The below methods worked for testing for strings. Using 4 backslashes did not work either. decimal.TryParse is not working as well. Can someone please offer insight. Thanks.
error 1 Regex: Cannot convert from decimal to string
error 2 TryParse: Cannot convert from decimal to System.ReadOnlySpan
Console.WriteLine("Please enter a number");
decimal enteredNumber1 = decimal.Parse(Console.ReadLine());
if (!Regex.IsMatch(enteredNumber1,"^[0-9]\\\\d{0,9}(\\\\.\\\\d{1,3})?%?$"))
{
Console.WriteLine("Numbers only");
}
if (!decimal.TryParse(enteredNumber1, out enteredNumber1))
Console.WriteLine("Numbers only");

Related

Printing a number with either one decimal place or none

Is there a simple way to print a number with either one decimal place or none?
I've searched the net for a method to do that but all of them try to always have a zero after the decimal point..
I want 3.0 to be printed as just 3, and 3.5 to be printed as 3.5.
I tried print('{:.1f}'.format(num)) but this prints 3.0
You have not specified the programming language, so I will provide an answer in pseudocode.
Using if-else
printWithOneOrNoDecimals(n)
if (isNumberInteger(n))
printWithoutDecimals(n)
else
printNumberWithOneDecimal(n)
isNumberInteger(n)
return round(n) == n
The method round(n) should round the number, for example 2.4 to 2. Because 2.4 != 2, isNumberInteger(2.4) would return false and the else statement is exectuted.
Now you can define different formats for printing numbers with or without decimal in printNumberWithOneDecimal and printWithoutDecimals.
Using “right trim” or “right strip”
Another way to achieve the result is to first make the number a string (maybe formatting it to have one decimal) and then “trimming” or “stripping” it from the right, first “all” zeros (in your case at most one) and then the decimal point (if any on the right). Note: trim or strip methods do not give an error if there’s nothing to trim/strip.
I guess that in Python it would be:
'{:.1f}'.format(num).rstrip('0').rstrip('.')
Happy coding, good luck!

How to specify a range in Ruby

I've been looking for a good way to see if a string of items are all numbers, and thought there might be a way of specifying a range from 0 to 9 and seeing if they're included in the string, but all that I've looked up online has really confused me.
def validate_pin(pin)
(pin.length == 4 || pin.length == 6) && pin.count("0-9") == pin.length
end
The code above is someone else's work and I've been trying to identify how it works. It's a pin checker - takes in a set of characters and ensures the string is either 4 or 6 digits and all numbers - but how does the range work?
When I did this problem I tried to use to_a? Integer and a bunch of other things including ranges such as (0..9) and ("0..9) and ("0".."9") to validate a character is an integer. When I saw ("0-9) it confused the heck out of me, and half an hour of googling and youtube has only left me with regex tutorials (which I'm interested in, but currently just trying to get the basics down)
So to sum this up, my goal is to understand a more semantic/concise way to identify if a character is an integer. Whatever is the simplest way. All and any feedback is welcome. I am a new rubyist and trying to get down my fundamentals. Thank You.
Regex really is the right way to do this. It's specifically for testing patterns in strings. This is how you'd test "do all characters in this string fall in the range of characters 0-9?":
pin.match(/\A[0-9]+\z/)
This regex says "Does this string start and end with at least one of the characters 0-9, with nothing else in between?" - the \A and \z are start-of-string and end-of-string matchers, and the [0-9]+ matches any one or more of any character in that range.
You could even do your entire check in one line of regex:
pin.match(/\A([0-9]{4}|[0-9]{6})\z/)
Which says "Does this string consist of the characters 0-9 repeated exactly 4 times, or the characters 0-9, repeated exactly 6 times?"
Ruby's String#count method does something similar to this, though it just counts the number of occurrences of the characters passed, and it uses something similar to regex ranges to allow you to specify character ranges.
The sequence c1-c2 means all characters between c1 and c2.
Thus, it expands the parameter "0-9" into the list of characters "0123456789", and then it tests how many of the characters in the string match that list of characters.
This will work to verify that a certain number of numbers exist in the string, and the length checks let you implicitly test that no other characters exist in the string. However, regexes let you assert that directly, by ensuring that the whole string matches a given pattern, including length constraints.
Count everything non-digit in pin and check if this count is zero:
pin.count("^0-9").zero?
Since you seem to be looking for answers outside regex and since Chris already spelled out how the count method was being implemented in the example above, I'll try to add one more idea for testing whether a string is an Integer or not:
pin.to_i.to_s == pin
What we're doing is converting the string to an integer, converting that result back to a string, and then testing to see if anything changed during the process. If the result is =>true, then you know nothing changed during the conversion to an integer and therefore the string is only an Integer.
EDIT:
The example above only works if the entire string is an Integer and won’t properly deal with leading zeros. If you want to check to make sure each and every character is an Integer then do something like this instead:
pin.prepend(“1”).to_i.to_s(1..-1) == pin
Part of the question seems to be exactly HOW the following portion of code is doing its job:
pin.count("0-9")
This piece of the code is simply returning a count of how many instances of the numbers 0 through 9 exist in the string. That's only one piece of the relevant section of code though. You need to look at the rest of the line to make sense of it:
pin.count("0-9") == pin.length
The first part counts how many instances then the second part compares that to the length of the string. If they are equal (==) then that means every character in the string is an Integer.
Sometimes negation can be used to advantage:
!pin.match?(/\D/) && [4,6].include?(pin.length)
pin.match?(/\D/) returns true if the string contains a character other than a digit (matching /\D/), in which case it it would be negated to false.
One advantage of using negation here is that if the string contains a character other than a digit pin.match?(/\D/) would return true as soon as a non-digit is found, as opposed to methods that examine all the characters in the string.

is there a way to convert an integer to be always a 4 digit hex number using Lua

I'm creating a Lua script which will calculate a temperature value then format this value as a 4 digit hex number which must always be 4 digits. Having the answer as a string is fine.
Previously in C I have been able to use
data_hex=string.format('%h04x', -21)
which would return ffeb
however the 'h' string formatter is not available to me in Lua
dropping the 'h' doesn't cater for negative answers i.e
data_hex=string.format('%04x', -21)
print(data_hex)
which returns ffffffeb
data_hex=string.format('%04x', 21)
print(data_hex)
which returns 0015
Is there a convenient and portable equivalent to the 'h' string formatter?
I suggest you try using a bitwise AND to truncate any leading hex digits for the value being printed.
If you have a variable temp that you are going to print then you would use something like data_hex=string.format("%04x",temp & 0xffff) which would remove the leading hex digits leaving only the least significant 4 hex digits.
I like this approach as there is less string manipulation and it is congruent with the actual data type of a signed 16 bit number. Whether reducing string manipulation is a concern would depend on the rate at which the temperature is polled.
For further information on the format function see The String Library article.

Grails - Inputfields shows a dot ('.') instead of (',') for decimal numbers

In an edit.gsp, where I have inputfields for decimal number, the decimal number show up as '3.123' and if I save it: I got error as the decimal point is wrong! It expect a ','. My locale is Sweden.
So I have to manually replace dot's with comma for all decimal numbers.
I've looked around the whole week and could not find a solution anywhere.
Shouldn't Grails be consistent and show commas when it expect commas in the save?
It should work with both BigDecimal and for double.
I have Grails 3.2.4
Here is an example of a "g:field" from an edit-form:
Bredd: <g:field type="number decimal" name="width" min="20" max="300" required="Y" value="${request1?.width}" style="width: 4em"/>
So, what can I do?
manually replacing dots sounds all horrible and possibly the wrong approach.
Moved answer segments around
So an update on the answer since i hit a similar issue today maybe in reverse. Sent through a number of 3333 when validation failed for another reason the number in the field had become 3,333 after the validation failure. If the old validation issue is fixed it will now fail due to comma in the number.
The reason turned out to be :
<g:textField value="${fieldValue(bean: instance, field: 'someField')}"
upon return changed number to 3,333 when changing this to
value="${instance.someField}"
Above was actual issue #larand was facing
I would store the input field width as a short
so :
Class MyClass {
//if you are storing a number like 123 (non decimal)
Short width
//if you are storing 12.12 which becomes 1212 when stored
Integer width
BigDecimal getDecimalWidth() {
return new BigDecimal(this.width).movePointRight(2).setScale(2)
}
void setWidth(BigDecimal decimal) {
this.width=new BigDecimal(decimal).movePointLeft(2).setScale(2)
}
//unsure but think this should work
Integer getWidthInteger() {
return this.width as int
}
void setWidth(Integer integer) {
this.width=(byte)integer
}
}
This will then give you methods to get the short value as big decimal using ${instance.decimalWidth} or as integer : ${instance.widthInteger}
when your field is actually numeric:
<g:formatNumber number="${myCurrencyAmount}" type="currency" currencyCode="EUR" />
To me that seems a lot more straight forward and cleaner than chopping up numbers which well you think about it
After first validation issue the number was 3333 as put in. So maybe this is your issue ? Unsure since you are talking of dots

Lua script - find digits in a string

I have a Cisco ASA 8.4 VPN Concentrator. I am trying to use Lua to extract digits from a certificate string coming in and use them in a LDAP lookup with AD for authorization. I found a string that works...sometimes.
The string comes in with the format:
LAST_NAME.FIRST_NAME.MIDDLE_NAME.1234567890
My LDAP only wants to see the digits and #domainname. The script I am currently us is: return string.gsub(cert.subject.cn, "^(%w+)%.(%w+)%.(%w+)%.(%w+)$", "%4#domain")
This script works fine in most cases (80-90% of the time). When it doesn't work is when people have no middle name, 4 names instead of 3, etc.
My question is how can I get it to output only the 10 digits, regardless of what comes before it. Seems too easy with a return string.match, but so far I can't get it to work. Any ideas?
You can use the pattern .*(%d%d%d%d%d%d%d%d%d%d)$:
local str = 'LAST_NAME.FIRST_NAME.MIDDLE_NAME.1234567890'
print(str:match('.*(' .. ('%d'):rep(10) .. ')$'))
or .*(%d+)$ if the number of digits is always 10.
If the 10 digits is always the last 10 characters, this works:
print(str:sub(-10, -1))

Resources