473,326 Members | 2,126 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Help, how can you parse a decimal and ...

I am looking for the easiest way to parse a float number.

X.Y where X=>0 and X <=5 and Y = 0 or Y = 5

e.g. the number should be one of the following 1 1.0 1.5 2 2.0 2.5 etc.

I tired using regular expressions, with no luck.

Thanks,
Karim
Jul 20 '05 #1
11 16244


Karim wrote:
I am looking for the easiest way to parse a float number.

X.Y where X=>0 and X <=5 and Y = 0 or Y = 5

e.g. the number should be one of the following 1 1.0 1.5 2 2.0 2.5 etc.

I tired using regular expressions, with no luck.


I think
var numberPattern = /^[0-5]\.[05]$/;
meets your requirements

--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #2
Martin,

I tried that, but it only works for 1.0 1.5 2.0 2.5 etc but not 1 2 3 4
5. Is there another way?

Thanks,
Karim

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #3
Karim Kabbara <kk******@bu.edu> writes:
Martin,

I tried that, but it only works for 1.0 1.5 2.0 2.5 etc but not 1 2 3 4
5. Is there another way?


var numberPattern = /^[0-5](\.[05]|)$/;

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #4
I bow to you Lasse.Thanks!

One more addition, I am calculating three fields as-well-as validating.
I came up with the following code.

function SumTotal()
{
var raps = parseFloat(document.Form.score.value);
var lrs = parseFloat(document.Form.score1.value);
var is = parseFloat(document.Form.score2.value);

document.Form.SumTotal1.value = (raps+lrs+is);
}

function checknumeric(field)
{
pattern = /^[0-5](\.[05]|)$/;

if(pattern.test(field.value)==false)
{
alert("You can only use 1 to 5 and .5");
}
}

I would like to add the Checknumeric with each field being entered.
Would I use the function with each field or?

Thanks in advance.

Karim

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #5
Karim Kabbara <kk******@bu.edu> writes:
One more addition, I am calculating three fields as-well-as validating.
I came up with the following code.

function SumTotal()
{
I would make a variable holding the form here, to save time and
space:
var form = document.forms['Form'].elements;
var raps = parseFloat(document.Form.score.value);
and then just write
var raps = parseFloat(form.score.value);
It is not saving a lot, but I think it is easier to read :)

You want the values of these three to be between 0 and 5.5 in one-half
increments. So, you need to check each one.

I assume you want to check them before converting with parseFloat, to
rule out inputs of the form "2.5arglebargle".

For simplicity, I think I would combine the conversion and check:

function checkAndConvert(string) {
if (! (/^[0-5](\.[05])?$/).test(string)) {
alert("The input '"+string+"' is not between 0 and 5.5 in "+
"increments of one half");
return; // returns undefined
}
return +string; // converts to number faster than parseFloat.
}

Then:

function SumTotal() {

var form = document.forms['Form'].elements;

var raps = checkAndConvert(form.score.value);
var lrs = checkAndConvert(form.score1.value);
var is = checkAndConvert(form.score2.value);

if (raps === undefined ||
lrs === undefined ||
is === undefined) {
return;
}

form.SumTotal1.value = (raps+lrs+is);
}
I would like to add the Checknumeric with each field being entered.
Would I use the function with each field or?


In some way, yes.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #6
Lasse,

Thanks again. It works, but I am using the onChange function, so if I
change each field it calculates all the fields, I need to check the
validation on !this field then add to the total everytime I change to
the next field.

The algorithim would be validate num with rule 0 to 5 with .5
increments. Then add and total the num.

Do you think I need an array to do this?

Regards,
Karim
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #7
Oh yes, I forgot to add, I should use the focus function if the num is
not valid. So when they change focus and it does not satisfy the
condition, it place's them back on the field to change.

Karim

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #8
Karim Kabbara <kk******@bu.edu> writes:
Oh yes, I forgot to add, I should use the focus function if the num is
not valid. So when they change focus and it does not satisfy the
condition, it place's them back on the field to change.


This is a dangerous thing to do. It traps people in the field. Good
thing it isn't the onblur handler, since this way, they can get away
from the input field by trying to leave it twice (the second time,
there is have been no change, so the onchange handler doesn't
trigger). Don't change it to onblur!

You can collect all the values each time you want to update the result,
or you can cache them. Here I cache them in an object instead of in an
array, together with their sum.

---
var values = {raps:0,lrs:0,is:0,total:0};

function checkAndAdd(elem) {
if (!/^[0-5](\.[05])?$/.test(elem.value)) {
alert("Input illegal: "+elem.value);
setTimeout(function(){elem.focus();},20); // [1]
return;
}
var value = +elem.value;
values.total += value - values[elem.name];
values[elem.name] = value;
elem.form.elements['SumTotal1'].value = values.total;
}
---
Then you can call this function from each element:
---
<input type="text" name="raps" value="0" onchange="checkAndAdd(this)">
<input type="text" name="lrs" value="0" onchange="checkAndAdd(this)">
<input type="text" name="is" value="0" onchange="checkAndAdd(this)">
---
[1] The delay is for browsers which change the focus to the next
element *after* executing the onchange event handler, overriding
the focus set in the handler.

Hope this works :)
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #9
JRS: In article <3f******@olaf.komtel.net>, seen in
news:comp.lang.javascript, Martin Honnen <Ma***********@t-online.de>
posted at Sat, 27 Sep 2003 16:11:40 :-
Karim wrote:
I am looking for the easiest way to parse a float number.

X.Y where X=>0 and X <=5 and Y = 0 or Y = 5

e.g. the number should be one of the following 1 1.0 1.5 2 2.0 2.5 etc.

I tired using regular expressions, with no luck.


I think
var numberPattern = /^[0-5]\.[05]$/;
meets your requirements


That seems to fit the description.
var numberPattern = /^[1-5](\.[05])?$/; // fits the example

I wonder whether he actually wants 5.5 ?

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)
Jul 20 '05 #10
Yes, I am not trying to get 5.5 my max is 5. Also, I tried the code and
I am getting Object not found. The sample is below.Thanks

<script language="Javascript">
var values = {raps:0,lrs:0,isc:0,total:0};

function checkAndAdd(elem) {
if (!/^[0-5](\.[05])?$/.test(elem.value)) {
alert("Input illegal: "+elem.value);
setTimeout(function(){elem.focus();},20); // [1]
return;
}
var value = +elem.value;
values.total += value - values[elem.name];
values[elem.name] = value;
elem.form.elements['SumTotal1'].value = values.total;
}
</script>
<table>
<tr>
<td>RAPS</td>
<td><input maxlength="10" size="10" value="" name="raps"
onchange="checkandadd(this)"></td>
</tr>

<tr>
<td >LRS</td>
<td ><input maxlength="10" size="10" value="" name="lrs"
onchange="checkandadd(this)"></td>
</tr>

<tr>
<td >IS</td>
<td ><input maxlength="10" size="10" value="" name="isc"
onchange="checkandadd(this)"></td>
</tr>

<tr>
<td align="right"><span style="FONT-SIZE: 12pt">Overall
Score (0-15):
<o:p></o:p>
</span> </td>
<td ><strong><input id="SumTotal1" readonly name="SumTotal1"
style="WIDTH: 79px; HEIGHT: 22px"

size="10"></strong></td>
</tr>

</table>

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #11
Karim Kabbara <kk******@bu.edu> writes:
Yes, I am not trying to get 5.5 my max is 5. Also, I tried the code and
I am getting Object not found. The sample is below.Thanks <script language="Javascript">
Use
<script type="text/javascript">
instead. The type attribute is required in HTML 4.
var values = {raps:0,lrs:0,isc:0,total:0};

function checkAndAdd(elem) {
if (!/^[0-5](\.[05])?$/.test(elem.value)) {
If you didn't want 5.5, the regular expression would have to change, e.g.,
if (!/^(([0-4](\.[05])?)|(5(\.0)?))$/.test(elem.value)) {

or perhaps using a simple comparison with the regular expression:

if (!/^[0-5](\.[05])?$/.test(elem.value) || elem.value > 5) { elem.form.elements['SumTotal1'].value = values.total;
There is no form around your input elements (which I assumed there
would be), so this fails. Have to change it to:

document.getElementById("SumTotal1").value = values.total;
onchange="checkandadd(this)"></td>
Javascript is case sensitive. This should be

onchange="checkAndAdd(this)"></td>

with capital A's.
This goes for all three inputs.
<td ><strong><input id="SumTotal1" readonly name="SumTotal1"
style="WIDTH: 79px; HEIGHT: 22px"


You don't need the name attribute on this input. Also, the strong tag
isn't affecting the contents of the input in my browser. You would
probably get a better result by adding "font-weight:bold;" to the style
attribute.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Johnny | last post by:
I need to determine whether a text box contains a value that does not convert to a decimal. If the value does not convert to a decimal, I want to throw a MessageBox to have the user correct the...
3
by: Mark | last post by:
How do you parse a currency string to a decimal? I'd like to avoid having to parse the number out, removing the $ manually. That sounds like a hack. There are times that this string will be...
2
by: probashi | last post by:
Hi, I am trying to the following: String s = "( 54.05)"; decimal d = decimal.Parse(s); when s = "( 54.05)" I what the value -54.05 and s = " 54.05" I what the value 54.05
3
by: Slonocode | last post by:
I have some textboxes bound to an access db. I wanted to format the textboxes that displayed currency and date info so I did the following: Dim WithEvents oBidAmt As Binding oBidAmt = New...
1
by: Mythran | last post by:
Dim value As Decimal = 1234.56 Dim format As String = _ "Positive $#,##0.00;Negative $#,##0.00;" Dim s As String = value.ToString(format) Dim d As Decimal = Decimal.Parse(s) The last line...
13
by: Jason | last post by:
Could someone here show me how I would write a vb program to convert decimal ip address to binary? For example a small form with a convert button and a label for the result and a textbox for the...
2
by: PJHORNSA | last post by:
Hi all, I got a problem.. I want to format the time into a decimal value.. The code that I used worked fine for some time but now it does not want to work.... If any one can help me or give me...
5
by: Navid Azimi | last post by:
What's the best way to parse a currency string to a decimal given the possibility of multiple currencies? That is, my numeric string can be ($12.00) or -£12.00; in either case I want -12.00 to be...
3
by: vanidosa27 | last post by:
I need to write a code that calculates the change due after the user has input the amount owed and amount paid. This is easy enough! :rolleyes: My problem comes in when the program wants you to...
3
by: Andrew Wrigley | last post by:
Hi, I have a string: "100.00" ....that I want to parse into a decimal. So: decimal d = decimal.Parse("100.00", System.Globalization.NumberStyles.Any) On my dev machine (United Kingdom),...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.