/    Sign up×
Community /Pin to ProfileBookmark

string conversion

i am taking a value from user input, lets say $5,000.00

I want to be able take the input and do some simple math to it. i thought it would be best to make the val a string at first and take out any char except a number 0 – 9. is there a faster way to do this?

right now i am taking the amount from a TFmail formail cgi script. The string passes through fine. but, if there are any char’s like ‘$’ or ‘,’ in the string then the output is obviously garbage. what would be the most efficient way to code this for faster page loads? anyway to get around iterating through the entire string?

var str=”{= param.amount =}”;
var amt= 100 + (.01 * parseInt(str));
document.write(amt);

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@JonaNov 18.2004 — <i>
</i>str = str_replace(/[$,]/g, str);
Copy linkTweet thisAlerts:
@CharlesNov 18.2004 — [font=monospace]<script type="text/javascript">

<!--

String.prototype.reverse = function () {return this.split('').reverse().join('')};

function Dollars (d) {this.ammount = typeof d == 'number' ? d : Number(d.toString().replace(/[$,]/g, ''))};

Dollars.prototype.valueOf = function () {return this.ammount};

Dollars.prototype.toString = function () {

if (isNaN (this.ammount)) return NaN.toString();

var l = Math.floor(Math.abs(this.ammount)).toString();

var r = Math.round((Math.abs(this.ammount) % 1) * 100).toString();

return [(this.ammount < 0 ? '-' : ''), '$', (l.length > 4 ? l.reverse().match(/d{1,3}/g).join(',').reverse() : l),'.', (r < 10 ? '0' + r : r)].join('');

}

var str='$10,000';

var amt= 100 + (.01 * new Dollars (str));

document.write(new Dollars (amt));

// -->

</script>[/font]
Copy linkTweet thisAlerts:
@jwbondauthorNov 18.2004 — i understand how the code works, i will have to look up some of the functions used for my own knowledge on it all.

the only problem is that it returns "NaN" if the input has a '$'


also how do I have it write to a specific place on the page instead of at the top?
×

Success!

Help @jwbond spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...