473,664 Members | 3,001 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Empty field giving me undefined

I have a function that formats currency to add commas and $.

But I also check to see if the field is empty and if it is I return.

The problem is that the field now contains the word "undefined" . I don't
want to have anything in this case.

Why is that word showing up and how do I tell it to do nothing?

function formatCurrency( num) {
if (num.Length == 0)return;
num = num.toString(). replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num))) ;
num = Math.floor(num* 100+0.500000000 01);
cents = num%100;
num = Math.floor(num/100).toString() ;
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num .length-(1+i))/3); i++)
num = num.substring(0 ,num.length-(4*i+3))+','+
num.substring(n um.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}

I call it as:

onBlur="this.va lue= formatCurrency( this.value)"

Thanks,

Tom
Jul 23 '05 #1
8 1853
tshad wrote:
I have a function that formats currency to add commas and $.

But I also check to see if the field is empty and if it is I return.

The problem is that the field now contains the word "undefined" . I don't
want to have anything in this case.

Why is that word showing up and how do I tell it to do nothing?

function formatCurrency( num) {
if (num.Length == 0)return;
if(!num.length) return "";

The rest of this function is pretty bad
num = num.toString(). replace(/\$|\,/g,''); It's going to be a string:
num = num.replace(/[$,]/g,'');

if(isNaN(num))
num = "0"; This could be a problem (with division by zero).
sign = (num == (num = Math.abs(num))) ; sign=num<0?"-":"";
num = Math.floor(num* 100+0.500000000 01); Why not the following?
num = num*100+""
num=num.substri ng(0,num.length-2)+"."+num.subs tring(num.lengt h-2);
return sign+"$"+num;

Mick cents = num%100;
num = Math.floor(num/100).toString() ;
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num .length-(1+i))/3); i++)
num = num.substring(0 ,num.length-(4*i+3))+','+
num.substring(n um.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}

I call it as:

onBlur="this.va lue= formatCurrency( this.value)"

Thanks,

Tom

Jul 23 '05 #2
On 06/04/2005 20:27, tshad wrote:
I have a function that formats currency to add commas and $.
Same here. :)

/* n - Number to format (in pennies).
* c - Currency symbol to use (defaults to none).
* t - Thousands separator (defaults to none).
* d - Decimal separator (defaults to '.').
*
* Outputs a number of the form cntnnntnnndnn
*
* For example, toCurrency(1426 35.7, '£', ',') produces
* £1,426.36
*/
function toCurrency(n, c, t, d) {
var s = (0 > n) ? '-' : ''; n = Math.abs(n);
var m = String(Math.rou nd(n));
var j, i = '', f; c = c || ''; t = t || ''; d = d || '.';

while(m.length < 3) {m = '0' + m;}
f = m.substring((j = m.length - 2));
while(j > 3) {
i = t + m.substring(j - 3, j) + i;
j -= 3;
}
i = m.substring(0, j) + i;
return s + c + i + d + f;
}

It's predominantly string-oriented, so floating-point errors are not a
concern. However, it takes a number as it's first argument, not a
string so you'll have to do your error checking beforehand.
The problem is that the field now contains the word "undefined" . [...]
Why is that word showing up and how do I tell it to do nothing?

function formatCurrency( num) {
if (num.Length == 0)return;
The length property begins with a lowercase L, so the function always
ends here. Unlike other languages, no return value does actually
return a value: undefined. This is then type-converted into the
string, 'undefined', when you assign to the value property.
num = num.toString(). replace(/\$|\,/g,'');
The num variable is already a string, to the toString call is unnecessary.
num = Math.floor(num* 100+0.500000000 01);


See, this is where string manipulation is preferred - no kludges needed.

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #3
Lee
tshad said:

I have a function that formats currency to add commas and $.

But I also check to see if the field is empty and if it is I return.

The problem is that the field now contains the word "undefined" . I don't
want to have anything in this case.

Why is that word showing up and how do I tell it to do nothing?

function formatCurrency( num) {
if (num.Length == 0)return;


There is no attribute named "Length".
It's "length".

if(!num.length) return;

Jul 23 '05 #4

"Michael Winter" <m.******@bluey onder.co.invali d> wrote in message
news:Hr******** *******@text.ne ws.blueyonder.c o.uk...
On 06/04/2005 20:27, tshad wrote:
I have a function that formats currency to add commas and $.
Same here. :)

/* n - Number to format (in pennies).
* c - Currency symbol to use (defaults to none).
* t - Thousands separator (defaults to none).
* d - Decimal separator (defaults to '.').
*
* Outputs a number of the form cntnnntnnndnn
*
* For example, toCurrency(1426 35.7, '£', ',') produces
* £1,426.36
*/
function toCurrency(n, c, t, d) {
var s = (0 > n) ? '-' : ''; n = Math.abs(n);
var m = String(Math.rou nd(n));
var j, i = '', f; c = c || ''; t = t || ''; d = d || '.';

while(m.length < 3) {m = '0' + m;}
f = m.substring((j = m.length - 2));
while(j > 3) {
i = t + m.substring(j - 3, j) + i;
j -= 3;
}
i = m.substring(0, j) + i;
return s + c + i + d + f;
}

It's predominantly string-oriented, so floating-point errors are not a
concern. However, it takes a number as it's first argument, not a string
so you'll have to do your error checking beforehand.


I am going to look at your function as it does look more clean.
The problem is that the field now contains the word "undefined" . [...]
Why is that word showing up and how do I tell it to do nothing?

function formatCurrency( num) {
if (num.Length == 0)return;


The length property begins with a lowercase L, so the function always ends
here. Unlike other languages, no return value does actually return a
value: undefined. This is then type-converted into the string,
'undefined', when you assign to the value property.


So how would I return at the top of the function if there is nothing in the
field?

Should I not return a value and just change the value inside of the
function? If this is the case, would I call the function something like:

onBlur=" return formatCurrency( this.value)"

or

onBlur="javascr ipt:formatCurre ncy(this.value) "

Not really sure why I would do it this way, but I see others call these
ways.

Thank,

Tom

num = num.toString(). replace(/\$|\,/g,'');


The num variable is already a string, to the toString call is unnecessary.
num = Math.floor(num* 100+0.500000000 01);


See, this is where string manipulation is preferred - no kludges needed.

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.

Jul 23 '05 #5
On 06/04/2005 22:08, tshad wrote:
So how would I return at the top of the function if there is nothing in the
field?
Return an empty string or '$0.00'. Whichever you prefer.
onBlur="javascr ipt:formatCurre ncy(this.value) "


The "javascript :" part would be unnecessary. Most user agents would
interpret that as nothing more than a statement label. Though IE would
attach some meaning to it, it would only be useful if you used
VBScript earlier in the document (which would be a bad idea on the Web).

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #6
"Michael Winter" <m.******@bluey onder.co.invali d> wrote in message
news:xo******** ********@text.n ews.blueyonder. co.uk...
On 06/04/2005 22:08, tshad wrote:
So how would I return at the top of the function if there is nothing in
the field?
Return an empty string or '$0.00'. Whichever you prefer.


It worked fine when I did:

if (num.length == 0)return "";
onBlur="javascr ipt:formatCurre ncy(this.value) "
The "javascript :" part would be unnecessary. Most user agents would
interpret that as nothing more than a statement label. Though IE would
attach some meaning to it, it would only be useful if you used VBScript
earlier in the document (which would be a bad idea on the Web).


Then what is the difference between:

onBlur="javascr ipt:formatCurre ncy(this.value) "

onBlur="return javascript:form atCurrency(this .value)"

Thanks,

Tom
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.

Jul 23 '05 #7
Lee
tshad said:

"Michael Winter" <m.******@bluey onder.co.invali d> wrote in message
news:xo******* *********@text. news.blueyonder .co.uk...
On 06/04/2005 22:08, tshad wrote:
So how would I return at the top of the function if there is nothing in
the field?


Return an empty string or '$0.00'. Whichever you prefer.


It worked fine when I did:

if (num.length == 0)return "";
onBlur="javascr ipt:formatCurre ncy(this.value) "


The "javascript :" part would be unnecessary. Most user agents would
interpret that as nothing more than a statement label. Though IE would
attach some meaning to it, it would only be useful if you used VBScript
earlier in the document (which would be a bad idea on the Web).


Then what is the difference between:

onBlur="javasc ript:formatCurr ency(this.value )"

onBlur="retu rn javascript:form atCurrency(this .value)"


The second is a syntax error. The label ("javascript :" in this case),
must appear first on the line.

If nobody else has mentioned it, it's a bad idea to use the onBlur
event of a text field, since there are so many uncontrollable and
unexpected things that can happen to cause a field to lose focus
before the user is done typing in it. Using onChange is cleaner.

Jul 23 '05 #8
JRS: In article <gd************ ******@twister. nyroc.rr.com>, dated Wed,
6 Apr 2005 20:00:12, seen in news:comp.lang. javascript, Mick White
<mw***********@ rochester.rr.co m> posted :
Why not the following?
num = num*100+""
num=num.substr ing(0,num.lengt h-2)+"."+num.subs tring(num.lengt h-2);
return sign+"$"+num;


You must be a newcomer ... <g> search back a few years in the group.

That's OK for num = 1.07 & 1.00, dubious for num = 0.99 & 0.90 (decimal
points should always be surrounded by digits), numerically wrong for
0.09 and 0.08, and amazing for 0.07, for which I get 7.0000000000000 .01
..

For reliable rounding, see the newsgroup FAQ and <URL:http://www.merlyn.
demon.co.uk/js-round.htm>.

For the insertion of thousands separators in numeric strings, see
<URL:http://www.merlyn.demo n.co.uk/js-maths.htm#Out> and in particular
<URL:http://www.merlyn.demo n.co.uk/js-maths.htm#Money >, after another
MW.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #9

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

Similar topics

1
5025
by: Wayno | last post by:
My php logs are coming up empty. I have done all I can think of, and all that made sense to me. Can someone take a look at my php.ini please and tell me what you think may be the problem. I double-checked the path to my error log. It is in /var/www/logs/php_error_log Thanks. :) -Wayne Stevenson
11
1365
by: WindAndWaves | last post by:
Hi Gurus What I would like to do is to setup a little form where people can put in a date (e.g. Day: Month..... Year , where ... is user input) and subsequently, will take them through to an anchor (<A NAME={date}></A>), relating to the date that they selected. As you may have worked out by now, I am a real novice when it comes to java script. I have a browse using Google, but so far no luck
5
2256
by: Thejo | last post by:
Hi all, I started programming in PHP recently and have a query about empty $_POST arrays. I can see two scenarios when this could happen. 1. When some tries to directly load the page to which data is being posted (for example, opening www.foo.com/xyz.php directly when a form action is xyz.php) 2. When the user clicks the submit button without entering anything.
11
3466
by: Bradford Chamberlain | last post by:
I work a lot with multidimensional arrays of dynamic size in C, implementing them using a single-dimensional C array and the appropriate multipliers and offsets to index into it appropriately. I tend to iterate over subsets of these arrays by walking a pointer and an offset per dimension across their dimensions. I've found that this tends to result in more performance in a portable manner than doing explicit indexing calculations and...
4
3184
by: whisher | last post by:
Hi. I'm taking my first steps on regex I set up this simple function to check if a form field is empty or with only space. var onlySpaceRegexp = /^\s*$/; function isEmpty(val) { if (onlySpaceRegexp.test(val) || val == "") {
6
37159
by: =?Utf-8?B?QmlsbEF0V29yaw==?= | last post by:
Hi, Thought this would be simple! If I want to validate a field that can contain "z" followed by 3 digits OR it's a completely empty string, how do I do that? The z123 bit is simple, but the empty string is giving me problems! e.g. ^\d{3}$| ....doesn't work (I thought the trailing "|" would detect the empty string). Thanks.
2
1610
by: Twinkle | last post by:
Can anyone please help me with the following. I have an empty Varchar column for one table. I need to convert the datatype to date now. But i need the field to be empty. How can this be done. When i tired ALTER TABLE TBL_PURCHASE_ORDER MODIFY PO_SUGG_SHIP_DT DATE; Its giving me the following error Incorrect date value: ' ' for column 'PO_SUGG_SHIP_DT' at row ...
8
19116
code green
by: code green | last post by:
I have been working with a script I have inherited that uses the ADODB class. I want to run a query that checks a record is unique across the primary key and date field in a MsSql DB before inserting, so I am using this function ADODB::Execute() to run this query SELECT 1 FROM table WHERE pk = 'code' AND eff_date = 'newdate'. Which hopefully returns an empty recordset. But when I call ADODB::RecordCount() to confirm the count is zero the...
7
2315
by: Moschops | last post by:
In moving some code from VS6 to VS2008 (bear with me, this is not a VS question, I'm just setting context), we find new crashes that weren't there before and we think they're related to trying an operation on a multimap that is empty - for example, std::multimap<double, aStructWeHaveDefined>::iterator low; low = c.begin() ; // c is empty (i.e. c.empty()==1) but we haven't checked for it In VS6 these crashed did not occur, in VS2008...
0
8437
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8348
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8861
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8549
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7375
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6187
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4185
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4351
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2003
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.