Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
Solved

# function to format a fixed digit number

Posted on 2008-06-13
Medium Priority
246 Views
Hello Folks,
I am using attached function to format some fixed digit number but it is giving me an error.
Please can you see if this is not correct?
thanks
s
``````<script>
function twoDecimal(num,round) {
if (round) return num.toFixed(2);
var stringNum = String(num);
if (stringNum.indexOf('.')==-1) return stringNum+'.00';
var newNum = stringNum.split('.');
if (newNum.len==2) {
newNum[1]=(newNum[1].length>2)?newNum[1].subString(0,2):newNum[1];
}
if (newNum[1].length==1) newnum[1]+="0"
return newNum[0]+'.'+newNum[1]
}

</script>
``````
0
Question by:newbie27
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 2

Accepted Solution

Airyck666 earned 2000 total points
ID: 21780787
Since the only time you can't use the .toFixed to solve this is if !round and there's more than 2 decimal places.  So try somethig this code.
``````<script>
function twoDecimal(num,round) {

var stringNum = String(num);
var newNum = stringNum.split('.');
if  (newNum.length > 1  && newNum[1].length > 1 && !round) {
newNum[1]=(newNum[1].length > 2) ? newNum[1].substring(0,2) : newNum[1];
return newNum[0]+'.'+newNum[1];
} else {
return String(num.toFixed(2));
}
}

</script>
``````
0

LVL 2

Assisted Solution

Airyck666 earned 2000 total points
ID: 21780800
oops... you don't need the String object creation at line 10.
``````return num.toFixed(2);
``````
0

LVL 8

Author Closing Comment

ID: 31466970
thanks
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be \$37.1B.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
###### Suggested Courses
Course of the Month11 days, left to enroll