Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

substringing

Status
Not open for further replies.

TheConeHead

Programmer
Joined
Aug 14, 2002
Messages
2,106
Location
US
How can I substring a number so that it always show the whole number plus two digits past the decimal? Meaning

1241234.345345 would show as 1241234.34

and

323.34534643 shows as 323.34

Math.Round() is not working so I am trying to substr....

[conehead]
 

If you don't mind the rounding, you could use toFixed:

Code:
alert(323.34534643.toFixed(2));

Hope this helps,
Dan

 
This should handle pretty much all situations (except multiple decimals):
Code:
<html>
<head>
<script language=javascript>
function returnNumber(str) {
   decLoc = str.indexOf(".");
   if (decLoc == -1) {
      return str + ".00";
   }
   return (str.length == decLoc + 1) ? (str + "00") : (str.length == decLoc + 2) ? (str + "0") : (str.substr(0, decLoc) + "." + str.substr(decLoc + 1, 2));
}
</script>
</head>
<body>
<form name=blahForm>
<input type=text name=blahText>Input the number here<br>
<input type=button value='click me' onclick='alert(returnNumber(blahForm.blahText.value))'>
</form>
</body>
</html>

-kaht

Weaseling out of things is important to learn. It's what separates us from the animals... except the weasel. - Homer Simpson (no, I'm not Homer)
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top