Welcome to WebmasterWorld Guest from 54.205.209.95

Forum Moderators: open

Message Too Old, No Replies

a way to limit decimal places with js

   
5:59 am on Nov 19, 2002 (gmt 0)

WebmasterWorld Administrator jatar_k is a WebmasterWorld Top Contributor of All Time 10+ Year Member



I have no idea, does anyone know of a way to do it?

I have a calculated dollar value that loves having tons of decimal places. In the past, I have always limited the size of the element but is there a better way?

6:07 am on Nov 19, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I used this in a function:

Math.round(n*100)/100

You'd have to add some code after that to add the extra 0's in case it was needed.

6:19 am on Nov 19, 2002 (gmt 0)

WebmasterWorld Administrator jatar_k is a WebmasterWorld Top Contributor of All Time 10+ Year Member



thanks dcheney,

perfect, my js isn't quite up to snuff these days, out of practice. That truncated beautifully. I guess I will have to add the trailing 0's but that can wait until tomorrow.

1:44 pm on Nov 19, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



<script type="text/javascript"> 
var olds = '2,346.4673292389';
var news = olds.replace(/^([\d,]+)\.(\d\d)\d*/,"$1.$2");
alert(news);
</script>

will work as well.

Andreas

4:32 pm on Nov 19, 2002 (gmt 0)

WebmasterWorld Senior Member txbakers is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Javascript doesn't have an elegant way of dealing with numbers.

I use a VB script function for this. You can mix the two on your pages.

function DoNumber(str, nDigitsAfterDecimal, nLeadingDigit, nUseParensForNeg, nGroupDigits)
if not isnull(str) then

DoNumber = replace(cstr(FormatNumber(str, nDigitsAfterDecimal, nLeadingDigit, nUseParensForNeg, nGroupDigits)),".",",")
lft = left(donumber,len(donumber) - 3)
rt = right(donumber,2)
donumber = lft & "." & rt
else
donumber = 0.00
end if
End Function

I left the "lft" and "rt" routines in just in case your DB like to use European formatting for numbers. I'm using mySql and never did figure out how to use US numbers. So I adapted my functions instead.

4:41 pm on Nov 19, 2002 (gmt 0)

10+ Year Member



Jatar:
This function will return a 2 place decimal rounded up or down accordingly:

function round(num){
num = num.toString();
var split = num.split(".");
var dec = split[1].substr(0,3);
var dec1 = dec.match(/\d{2,2}/);
var dec2 = dec.match(/(\d$)/);
var rounded = (dec1 + "." + dec2[0]);
return split[0] + "." + Math.round(rounded);
}
4:55 pm on Nov 19, 2002 (gmt 0)

10+ Year Member



I once found a js implementation of printf.

You can take a look at the script translated from Italian here [translate.google.com]

While not perfect, it does give some basic formatting capability:

js> sprintf("%3.4e", 3.345235423545);
3.3452

I found it floating on the net, so I believe it can be used freely. The authors email is within.

René-

[edited by: heini at 6:56 pm (utc) on Nov. 19, 2002]