...

View Full Version : Formatting Numbers in Javascript



tbrand
07-18-2011, 08:00 PM
I am creating a calculator app and I'm a bit stuck with number formatting.

Example of how I would like a number to be formatted:
$2,899,799

I currently have the formatting working except for the commas. I'm using the following code to achieve this.
My result is currently showing up like this $2899799


function format (expr, decplaces) {
var str = "" + Math.round (eval(expr) * Math.pow(10,decplaces))
while (str.length <= decplaces) {
str = "0" + str
}
var decpoint = str.length - decplaces
return str.substring(0,decpoint) + str.substring(decpoint,str.length);
}

function dollarize (expr) {
return "$" + format(expr,0)

//RESULT FIELDS
form.AnnualScrapSales.value = dollarize(((A - B) * (C2/100)) * G2)

is there a way to add to this "function format" code to also achieve the commas?

siberia-man
07-18-2011, 08:23 PM
Find answers for your questions here http://www.codingforums.com/showpost.php?p=1004098&postcount=5. Go back for more details if you need them. (-:

tbrand
07-18-2011, 08:31 PM
RE: Siberia-man

I'm afraid that I'm not really sure how I would integrate that code into my already existing code. I attempted to simply add it to my function format code like this:


function format (expr, decplaces) {
var str = "" + Math.round (eval(expr) * Math.pow(10,decplaces))
while (str.length <= decplaces) {
str = "0" + str
}
var decpoint = str.length - decplaces
return str.substring(0,decpoint) + str.substring(decpoint,str.length);
}
Number.prototype.$ = function()
{
var n = Math.abs(this).toFixed(2);

while ( arguments.callee.re.test(n) ) {
n = n.replace(arguments.callee.re, '$1,');
}

return (this < 0 ? '-$' : '$') + n;
};

Number.prototype.$.re = /(\d)(?=\d\d\d(?:,|\.))/;

var n = 12;
alert(n.$());

It didn't do anything when I tested.

siberia-man
07-18-2011, 08:34 PM
Hi tbrand,

Let's clarify your request to be sure that we are considering one thing.

You need format number with the following rules:

you have some numeric values -- for example, 123456789

1. you need insert commas to separate thousands with as here 123,456,789
2. you need add the dollar sign '$' as here $123,456,789

To achieve these just use the function that was suggested you



var n = 123456789;
var f = n.$(); // will result to the string '$123,456,789'


In your case -- do like this:


form.AnnualScrapSales.value = (((A - B) * (C2/100)) * G2).$();

tbrand
07-18-2011, 08:47 PM
Okay I will play around with this a bit. Thank you.

tbrand
07-18-2011, 09:35 PM
RE: Siberia-Man

Thank you for the suggestion - I did get it to work. Your second post was the clarification I needed. Thank you.

Only one issue with this - using this code I'm getting the two decimal places in my result field....I don't want any decimal places at all. Not even .00

I tried to change this as follows (see red) but after doing so the function doesn't work at all. Ideas?


Number.prototype.$ = function()
{
var n = Math.abs(this).toFixed(0);

while ( arguments.callee.re.test(n) ) {
n = n.replace(arguments.callee.re, '$1,');
}

return (this < 0 ? '-$' : '$') + n;
};

Number.prototype.$.re = /(\d)(?=\d\d\d(?:,|\.))/;

tbrand
07-18-2011, 09:52 PM
One more question.

In addition to getting rid of the decimal places ( I still haven't figured that one out yet) I'm also having trouble getting this code to work with the following result field:


form.RunQuantity.value = G

It works fine with all the other results, but can't seem to get it to do it with this one.

I've tried:
G.$();
(G).$();
(G.$());

no luck. I just get a blank field.

siberia-man
07-19-2011, 12:01 AM
Hi tbrand,

Nice to hear that this suggestion works for you. Answering for your first question I can recommend to apply the following modification (see marked substrings).



Number.prototype.$ = function(f)
{
var n = Math.abs(this).toFixed(f);

while ( arguments.callee.re.test(n) ) {
n = n.replace(arguments.callee.re, '$1,');
}

return (this < 0 ? '-$' : '$') + n;
};

Number.prototype.$.re = /(\d)(?=\d\d\d(?:,|\.|$))/;


The first and second marks are used to give more flexibility in usage. If you will need to show digits after a decimal point then you can use it with no changes. The third mark is related to your question directly -- apply to the code works properly.

Answering to your second question I can say exactly after you will give me more details on the 'G' variable -- i) what is it's value; ii) what is type of the 'G' variable; iii) where from have you got the 'G' variable?

tbrand
07-19-2011, 08:01 PM
Siberia-Man

Thank you once again, your tweak to the code fixed my problem of having the decimal places.

In regards to the "G" variable.

I have stated previously that this is a calculator app. To be more specific it's basically a quote estimator (or piece price estimator). We ask the user to input some information and then we calculate various results based upon their inputs.

One thing we ask the user is what the annual volume of their part is. They pick a number from a drop down list and this is what my variable G is.

Javascript to define var G:


var G = document.getElementById('annualvolume').value;
var GArr=new Array("2000","3000","3500","4200","4500","6000","10000","20000");
var GArr2=new Array("10000","30000","50000","100000","150000","300000","500000","1000000" )
for (i in GArr)
{
if (G == GArr[i])
{
var G2 = GArr2[i];
}
}

HTML for the drop down:

<li data-role="fieldcontain">
<p><span class="ui-listview-inset">Annual Volume:</label>
<select name="annualvolume" id="annualvolume">

onChange="Calculate();">
<option value="2000">10,000</option>
<option value="3000">30,000</option>
<option value="3500">50,000</option>
<option value="4200">100,000</option>
<option value="4500">150,000</option>
<option value="6000">300,000</option>
<option value="10000">500,000</option>
<option value="20000">1,000,000</option>
</select>
</p>
</li>

I hope this clarifies things for you.

Thank you again for your help : ) It is much appreciated.

siberia-man
07-19-2011, 08:48 PM
I see the root of this problem. The 'G' variable is string and you tries to apply the '$' method impelememted for a numeric type. To correct the problem you can use one of the three ways.

1. The best and simply undestandable way. Here we see that some variable 'G' (obviously it is a string variable) is converted to Number type and the '$' is called correctly.


... Number(G).$() ...


2. The second way is shorter but requires knowledge how variables are converted -- the unary plus considers any expression after itself as a number. So any string will be converted to a number even non-numeric value will be converted to a Not-A-Number value.


... (+G).$() ...


3. Multiple one will convert a string variable to a number too.


... (1 * G).$() ...


4. Call a method of one type in the context of another one. This wordy way and looks monstrously but it is very useful sometimes but not now. It is here to show that there are many ways to achieve the valid result.


... Number.prototype.$.call(G) ...

tbrand
07-19-2011, 09:16 PM
siberia-man:

You are genius man : )

... Number(G).$() ...
works fines in that it adds the comma, however I don't need the "$" on this result because it's not currency.

I apologize, I only somewhat understand how this script is working. I'm not sure how to tweak it myself to keep the comma but do away with the $ symbol.

siberia-man
07-19-2011, 09:32 PM
Heh =)

I saw in your first post that you need convert 123456 to '$123,456' etc.

Just replace the last line within a function with the simple return n. And keep your implementation of 'dollarize' function to insert a dollar sign before.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum