-
Hi,
I need a function that limit the decimal cases displayed in a dinamic text box, as the example:
"1,87939849343" to "1,87"
thanks
-
Gross Pecululatarian
I take it English isn't your native language, du to spelling and the , instead of . (Where all does that? I know Germany does). Anyway, heres a function:
Code:
dec = 345.4343433453;
function decLen(f,n){
var f = String(f);
var c = f.slice( 0,f.indexOf(".",0)+n+1);
return Number(c);
};
Ndec = decLen(dec,2); // = 345.43
-
or a quicker, one-line way to do it is:
(assuming "myNumber" is the number of which you want to limit the displayed digits.)
myNumber= int(myNumber*100)/100;
this basically will multiply the target number by 100 (multiplying by 100 will move the decimal point two digits to the right), then convert the number to an integer (hacking off everything after the decimal point), and then divides the number by 100 (thus moving the decimal point back two digits to the left) and leaving you with a happy semi-truncated floating-point number.
snarf,
brian.
-
Gross Pecululatarian
You dorty mind reader!
I just came back here, having had the same thought, only ot find you beat me too it
-
Senior Member
I needed something recently to literally have three characters only, regardless of the decimal point: ie
2.34
3.45
4.56 etc etc
this is what I came up with:
Code:
short = long.toString( radix ).substr(0,3);
also, this can be adapted for for timers (milliseconds timers, for example, where you may simply want the last 3 digits of a number
ie:
45565456
45565457
45565458
45565459
Code:
short = long.toString( radix ).substr(-3,3);
-
Senior Member
Just wanted to point out, that none of those work, if you need to round up numbers to certain decimal point, not just throw away all the rest
-
Senior Member
Originally posted by tonypa
Just wanted to point out, that none of those work, if you need to round up numbers to certain decimal point, not just throw away all the rest
this does:
myNumber= math.round((myNumber*100)/100);
-
Senior Member
I suppose you ment:
myNumber = math.round((myNumber*100))/100;
Lets see:
myNumber = 123.45499999
rounds with your code to: 123.45
I might be mistaken, but I think it should be 123.46
-
Senior Member
no it shouldn't, 123.45499999 rounded to 2 decimal places equals 123.45
-
I need to something slightly different.
need to go from
1.1234567890e-123 to 1.12e-123
I know you can chop off the exponent and the first 3 digit than put them back, but is there an easier way?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|