Support Forum Softcomplex logo
About Us  | Services  | Download  | Order  | Support  | |
| Search | Today's Posts | Stats | Board Rules | Not logged in [ Login | Register ]
go to bottom
Last active: Never

Printable Version | Subscribe | Add to Favourites   Post new thread
Author: Subject: Money (Currency) formatting JavaScript
tigra
Administrator

Posts: 2049
Registered: 6/17/2002
Location: US, CO
Member Is Offline
posted on 8/5/2005 at 11:50 PM Reply With Quote
Money (Currency) formatting JavaScript


This function will convert numeric value (interger or float) into the formatted currency:

Code:

function num2money(n_value) {

// validate input
if (isNaN(Number(n_value)))
return 'ERROR';

// save the sign
var b_negative = Boolean(n_value < 0);
n_value = Math.abs(n_value);

// round to 1/100 precision, add ending zeroes if needed
var s_result = String(Math.round(n_value*1e2)%1e2 + '00').substring(0,2);

// separate all orders
var b_first = true;
var s_subresult;
while (n_value > 1) {
s_subresult = (n_value >= 1e3 ? '00' : '') + Math.floor(n_value%1e3);
s_result = s_subresult.slice(-3) + (b_first ? '.' : ',') + s_result;
b_first = false;
n_value = n_value/1e3;
}
// add at least one integer digit
if (b_first)
s_result = '0.' + s_result;

// apply formatting and return
return b_negative
? '($' + s_result + ')'
: '$' + s_result;
}

View User's Profile View All Posts By User U2U Member
winotosw
Newbie

Posts: 1
Registered: 11/3/2007
Location: indonesia
Member Is Offline
posted on 11/3/2007 at 04:44 AM Reply With Quote
i found error for 1000,1000000,etc


i found error for y=num2money(x), where x=1000, x=1000000,x=1000000000,etc. y become: 000.00; 000000.00; 000000000.00
is it a bug for num2money function??
View User's Profile View All Posts By User U2U Member
tigra
Administrator

Posts: 2049
Registered: 6/17/2002
Location: US, CO
Member Is Offline
posted on 2/4/2009 at 09:39 PM Reply With Quote

yes, updated version:
Code:

function num2money(n_value) {
// validate input
if (isNaN(Number(n_value)))
return 'ERROR';

// save the sign
var b_negative = Boolean(n_value < 0);
n_value = Math.abs(n_value);

// round to 1/100 precision, add ending zeroes if needed
var s_result = String(Math.round(n_value * 1e2) % 1e2 + '00').substring(0, 2);

// separate all orders
var b_first = true;
var s_subresult;
while (n_value >= 1) {
s_subresult = (n_value >= 1e3 ? '00' : '') + Math.floor(n_value % 1e3);
s_result = s_subresult.slice(-3) + (b_first ? '.' : ',') + s_result;
b_first = false;
n_value = n_value / 1e3;
}
// add at least one integer digit
if (b_first)
s_result = '0.' + s_result;

// apply formatting and return
return b_negative
? '($' + s_result + ')'
: '$' + s_result;
}
View User's Profile View All Posts By User U2U Member
Post new thread

Related Links:

Go To Top


Powered by XMB 1.9.1 Nexus
Developed By Aventure Media & The XMB Group © 2002-2004