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!

Dollar Conversion 1

Status
Not open for further replies.

Lambro

Programmer
Joined
Aug 22, 2001
Messages
258
Location
US
Why is it when I enter a dollar amount with 2 decimal places does it round down the last digit? Say I enter 233.46 it will display 233.45

Heres my code:

<script>
function doIt(_f)
{
_f.t.value=convertIt(_f.t.value);
}
function convertIt(_v)
{
var _dollars=parseInt(_v);
var _cents=parseInt((_v-_dollars)*100);
var _negative=_dollars<0;
if(_negative){_dollars=-_dollars;_cents=-_cents;}
while(_cents.toString().length<2)_cents="0"+_cents;
var _dA=_dollars.toString().split("");
var _d="";
for(var i=_dA.length-1;i>=0;i--)
{
_d=_dA+_d;
}
var _neg_sign=_negative?"-":"";
var _result="$"+_neg_sign+_d+"."+_cents;
return _result;
}
</script>




<form>
<input name=t>
<input type=button onclick="doIt(this.form)" value="convert now">
</form>
 
JavaScript and its crazy handling of numbers!

Change this line:

Code:
var _cents=parseInt((_v-_dollars)*100);

...to:

Code:
var _cents=parseInt([b]Math.round([/b](_v-_dollars)*[b]1000[/b])[b]/10[/b]);

...and that should solve it for you. 'hope that helps!

--Dave
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top