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

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

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.

Thymeleaf converts integer to float with a decimal point. How can this be avoided?

If I have a tag like the below and the value test comes from a database and is an integer but th:text converts it to a floating point number e.g.....
<p th:text="${test}"/>
Where test....
{
"test": 5
}
the result is 5.0
However annoyingly if I use a number literal in thymeleaf e.g.
<p th:text="5+0"/>
the result is displayed correctly as 5
I know I can use something like <p th:text="${#numbers.formatDecimal(test,0,0)}"/> however this is problematic as I don't know if the value could be a number or not until runtime and so it will clutter it up with if statements etc. Would be so much better if it finds an integer to actually keep it as an integer (or convert it to a zero decimal text) - e.g. like it does with number literal. Is there any way to do this?
Many thanks for any help

How to convert Float to String with out getting E in blackberry

Any way to convert Float to string with out getting E (exponent).
String str = String.valueOf(floatvalue);
txtbox.settext(str);
and i am using NumericTextFilter.ALLOW_DECIMAL in my textField which allow decimal but not E.
i am getting like this 1.3453E7 but i want it something like 1.34538945213 due to e i am not able to set my value in edit text.
so any way to get value with out e.
I'm not 100% sure I understand what number you're trying to format. In the US (my locale), the number 1.3453E7 is not equal to the number 1.34538945213. I thought that even in locales that used the period, or full stop (.) to group large numbers, you wouldn't have 1.34538945213. So, I'm guessing what you want here.
If you just want to show float numbers without the E, then you can use the Formatter class. It does not, however, have all the same methods on BlackBerry that you might expect on other platforms.
You can try this:
float floatValue = 1.3453E7f;
Formatter f = new Formatter();
String str = f.formatNumber(floatValue, 1);
text.setText(str);
Which will show
13453000.0
The 1 method parameter above indicates the number of decimal places to show, and can be anything from 1 to 15. It can't be zero, but if you wanted to display a number without any decimal places, I would assume you would be using an int or a long for that.
If I have misunderstood your problem, please post a little more description as to what you need.
I'll also mention this utility class that apparently can be used to do more numeric formatting on BlackBerry, although I haven't tried it myself.
Try this:
Double floatValue = 1.34538945213;
Formatter f = new Formatter();
String result = f.format("%.11f", floatValue);
Due to the floating point presentation in java, the float value 1.34538945213 has not the same representation as the double value 1.34538945213. So, if you want to get 1.34538945213 as output, you should use a double value and format it as shown in the example.

check value starting with decimal ruby on rails

How do I check a value starting with a decimal
is_a_number(value) .... works for 12, 12.0, 12.2, 0.23 but not .23
Basically I'm doing a validation in a form, and I want to allow values starting with . i.e .23
but obviously pop up a flag (false) when its not a number
".23" isn't really a number, in my book.
If you want to treat it like one, check if the first character is a decimal point, if it is, prepend a "0" and try again.
Actually, you could probably prepend a zero regardless. It shouldn't affect the value of any "legitimate" number. (EDIT: As long as you can explicitly specify base 10 when actually converting to a number)
Read your input into a string and dynamically add the zero if needed. For example:
if (inputvar[0] == '.')
inputvar = "0#{inputvar}"
end
The resulting value can be converted into a number by .to_i, .to_f, etc.

Resources