2

How to Get number with 2 decimal and not rounding using javascript ?

i try

http://jsfiddle.net/3AaAx/31/

var i = "1234.666";
var xxx = Math.floor(i * 100) / 100
alert(xxx);

AND

http://jsfiddle.net/3AaAx/29/

var i = "1234.666";

function myToFixed(i, digits) {
    var pow = Math.pow(10, digits);

    return Math.floor(i * pow) / pow;
}
var xxx = myToFixed(i, 2)
alert(xxx);

it's work.

But when i declare var i = "1234"; i want to get "1234.00"

http://jsfiddle.net/3AaAx/30/

http://jsfiddle.net/3AaAx/32/

How to do that ?

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • *Not* rounding is an odd requirement. You really want `1234.5678` to result in `1234.56` not `1234.57` (which is closer to the truth)? – T.J. Crowder Dec 07 '14 at 14:47
  • have you tried this : `var xxx = 1234; var n = xxx.toFixed(2)` – scraaappy Dec 07 '14 at 14:49
  • @scraaappy - your function are rounding , when `var i = 1111.99;` – robert wisyert Dec 07 '14 at 14:52
  • 1
    possible duplicate of [Truncate (not round off) decimal numbers in javascript](http://stackoverflow.com/questions/4912788/truncate-not-round-off-decimal-numbers-in-javascript) – Sam Greenhalgh Dec 07 '14 at 14:53
  • well, if rounding is a problem you can always treat the number as a string (and use `indexOf` and `substring` the get the desired result) –  Dec 07 '14 at 14:54
  • no rounding with tofixed ! convert to a string is exactly the purpose of this method. See doc here: http://www.w3schools.com/jsref/jsref_tofixed.asp and try it with 111.99 or anything else, it works ! – scraaappy Dec 07 '14 at 14:57
  • @scraaappy: Again (see above), `toFixed` rounds. `(1234.5678).toFixed(2)` is `"1234.57"`. Or to use your example, `(111.99).toFixed(1)` is `"112.0"`; `(111.999).toFixed(2)` is `"112.00"`. The only reason `(111.99).toFixed(2)` doesn't round is that it's already only got two digits after the decimal. – T.J. Crowder Dec 07 '14 at 15:08
  • then you just have to set (1234.5678).toFixed(3) and remove last string character – scraaappy Dec 07 '14 at 15:13
  • @scraaappy: Nope: `(1234.9999).toFixed(3).substring(0, 7)` is `"1235.00"` – T.J. Crowder Dec 07 '14 at 15:15
  • var num = 1234.9999; var n = num.toFixed(10); alert(n.substring(0, n.length-8)); returns 1234.99 – scraaappy Dec 07 '14 at 15:35
  • 1
    @scraaappy: Please give it up, this is a waste of time, and I won't respond further. `(1234.99999999999).toFixed(10).substring(0, 14)` => `"1235.000000000"`. Again: Unless you already know the input number or do some operations ahead of time (which defeats the purpose of using it), you cannot use `toFixed` for this. – T.J. Crowder Dec 07 '14 at 15:48

2 Answers2

0

Not rounding is an unusual requirement, and it's too bad because if you were okay with rounding, you could just use toFixed:

var num = 1234.5678;
snippet.log(num.toFixed(2)); // "1234.57" -- note the rounding!

var num = 1234.5678;
snippet.log(num.toFixed(2)); // "1234.57" -- note the rounding!
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

(And no, you can't just do .toFixed(3) and then chop off the last digit; rounding doesn't necessarily only change the last digit, consider using toFixed(3) on 1111.9999, which gives you 1112.000. Just chopping off the last digit of that still gives you a rounded result.)

To do it without rounding, I don't think there's much available but brute force:

// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
  var parts = String(num).split('.');
  if (digits <= 0) {
    return parts[0];
  }
  var fractional = (parts[1] || "0") + "000000000000000000000";
  return parts[0] + "." + fractional.substring(0, digits);
}

// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
  var parts = String(num).split('.');
  if (digits <= 0) {
    return parts[0];
  }
  var fractional = (parts[1] || "0") + "000000000000000000000";
  return parts[0] + "." + fractional.substring(0, digits);
}

var num, notRounded;

num = 1234;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);

num = 1234.5678;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);

num = 1234.1;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);

num = 1234.999999;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Or you can use indexOf, but it seems a lot clunkier:

// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
  var str = String(num);
  var n = str.indexOf(".") + 1;
  if (n === 0) {
    str += ".";
    n = str.length;
  }
  n = digits <= 0 ? n - 1 : n + digits;
  if (str.length !== n) {
    str = (str + "00000000000000000000").substring(0, n);
  }
  return str;
}

// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
  var str = String(num);
  var n = str.indexOf(".") + 1;
  if (n === 0) {
    str += ".";
    n = str.length;
  }
  n = digits <= 0 ? n - 1 : n + digits;
  if (str.length !== n) {
    str = (str + "00000000000000000000").substring(0, n);
  }
  return str;
}

var num, notRounded;

num = 1234;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);

num = 1234.5678;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);

num = 1234.1;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);

num = 1234.999999;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • toFixed() method do the job – scraaappy Dec 07 '14 at 15:03
  • @scraaappy: `toFixed` *rounds*. The OP quite clearly said "not rounding." – T.J. Crowder Dec 07 '14 at 15:04
  • toFixed rounds only if you don't pass argument. `var num=11.9;alert(num.toFixed());` retuns 12, but `alert(num.toFixed(2));` returns 11.90 – scraaappy Dec 07 '14 at 15:10
  • @scraaappy: No, `toFixed` rounds, ***period***, if it can't fit the number in the space you give it. See the snippet at the beginning of the answer above. See [my comment](http://stackoverflow.com/questions/27343789/how-to-get-number-with-2-decimal-and-not-rounding-using-javascript/27343871?noredirect=1#comment43143377_27343789) on the question. Read [the spec](http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.5). Or [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed). All of these will show you that it rounds. – T.J. Crowder Dec 07 '14 at 15:11
  • yes sorry you're right, then see my last comment fior an easier solution ` var num = 1234.5678; var n = num.toFixed(3); alert(n.substring(0, n.length-1));` – scraaappy Dec 07 '14 at 15:16
  • @scraaappy: Nope, see [my reply comment](http://stackoverflow.com/questions/27343789/how-to-get-number-with-2-decimal-and-not-rounding-using-javascript/27343871?noredirect=1#comment43143518_27343789). You simply cannot use `toFixed` for this (unless you already know the input number). If you'd please remove your comments, I'll do the same. – T.J. Crowder Dec 07 '14 at 15:17
  • ok, ok ;) ... but !!! you can do something like that, no ? : `var n= num.toFixed(36); alert(n.substring(0, n.length-34));` It looks like the expected result, no? ;) – scraaappy Dec 07 '14 at 15:26
  • @scraaappy ***sigh*** Again, please read the spec or MDN: Max number you can give `toFixed` is `20`, and of course, `20` doesn't work: `(11.999999999999999999999).toFixed(20).substring(0, 22)` gives you (wait for it) `"12.0000000000000000000"` – T.J. Crowder Dec 07 '14 at 15:46
  • @TJCrowder I'm very sorry to insist but have you tried your code with your own example ? `var num, notRounded; num = 11.999999999999999999999; notRounded = toFixedNoRounding(num, 2); snippet.log(num + " => " + notRounded);` output is 12 ! number format in javascript is a double-precision floating-point format with 17 digits of precision. So my solution seams to work as you've mentionned max value of toFixed method is 20 (>to presicion) – scraaappy Dec 07 '14 at 17:08
  • @scraaappy: My bad on that number. The problem isn't my code or yours, though, it's that `11.999999999999999999999` **is** `12` (try it in the console). In fact, you can take several `9`s off the end and because of floating-point imprecision, it's still `12`. But the fundamental point remains: Using something that rounds as the basis for an operation that doesn't round makes no sense. – T.J. Crowder Dec 08 '14 at 07:30
-1
  var y = "1234.045";
  var s = number_with_2_decimal(y);
  alert(s);

  function number_with_2_decimal(a) {
  var x = Math.floor(a * 100) * 0.01;
  var str = String(x);
  var n = str.indexOf('.');
  if (n === -1) {
       str += '.00';
  };
  return str;
  }
jjpcondor
  • 1,386
  • 1
  • 19
  • 30