English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I've managed to get JavaScript to round to 2 places using:
Math.round(x*100)/100
However if x = 6 it displays as '6' rather than '6.00' which I want.

2007-01-12 01:50:51 · 4 answers · asked by Yak 2 in Computers & Internet Programming & Design

4 answers

Javascript has a built in method to do this on the Number object:

var x = new Number(25);
document.write(x.toFixed(2));

2007-01-12 09:12:46 · answer #1 · answered by rob_crowther_uk 4 · 2 0

Js Round To 2 Decimal

2016-11-04 03:39:16 · answer #2 · answered by Anonymous · 0 0

First, I have never programmed with JavaScript.

However, if you always expect two trailing zeros, then I would try to display the 6 as a string and simply concatenate ".00" to the end.

Without more information about your program, there's no way to tell if this solution would be sufficient. Also, having zero experience with JavaScript, I'm not even 100% sure that it's possible.

2007-01-12 02:41:25 · answer #3 · answered by Phillip W 2 · 0 1

The simplest solution would be to use a function to format your number. Change the name of the function to whatever suits you and edit the return statement to however you want to format the string.

function Currency( value) {
var temp = "" + (Math.round( value * 100));

return "$" + temp.slice(0,-2) + "." + temp.slice(-2);
}

alert( Currency(25));

2007-01-12 05:24:01 · answer #4 · answered by Kookiemon 6 · 0 1

fedest.com, questions and answers