39

How to get following inputs to bellow outputs

Input

1.0789
10.350
1.7777

Output

1.07
10.35
1.77
GG.
  • 21,083
  • 14
  • 84
  • 130
I don't know
  • 701
  • 2
  • 8
  • 15

2 Answers2

88

Use Math.floor to round the decimal places under the current value.

Reference

Example

Math.floor(1.0789 * 100) / 100

Working Fiddle

console.log(Math.floor(1.0789 * 100) / 100);
console.log(Math.floor(10.350 * 100) / 100);
console.log(Math.floor(1.7777 * 100) / 100);
console.log(Math.floor(12.34 * 100) / 100);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
  • 1
    it's not a round down – I don't know Dec 21 '16 at 09:53
  • If you are looking for under rounding. you need to use Math.floor – Nitheesh Dec 21 '16 at 09:58
  • Thanks. Its works dude.. – I don't know Dec 21 '16 at 10:13
  • You are welcome – Nitheesh Dec 21 '16 at 10:34
  • 8
    This does not work for values like 12.34 which are already 2 decimal places. 12.34 will turn into 12.33. A better solution `function floorDecimals(value, decimals) { return Number(Math.floor(value+'e'+decimals)+'e-'+decimals); }` Credit goes to here http://www.jacklmoore.com/notes/rounding-in-javascript/ – Sean Tomlins May 15 '18 at 23:31
  • 2
    @SeanTomlins The simple solution with multiply / divide seems to work for flooring and ceiling in Chrome and Firefox, for me at least. – vgel Jul 23 '20 at 19:39
  • @SeanTomlins note: this will not work with typescript. – Fiddle Freak Nov 22 '21 at 15:46
  • @FiddleFreak Typescript compiles to javascript, why will it not work? – Sean Tomlins Nov 23 '21 at 00:58
  • @SeanTomlins `Math.floor(3.29012 + 'e' + 3)` typescript error - "Argument of type 'string' is not assignable to parameter of type 'number'." – Fiddle Freak Nov 23 '21 at 21:10
  • 1
    @SeanTomlins Are you sure that this solution breaks for value `12.34`. I tested this solution with latest chrome, edge and IE. It still works as expected for me. – Nitheesh Nov 24 '21 at 03:39
  • Note that `Math.floor` **always** goes **down** the number scale, which may or may not be what you want with negative numbers. For instance, `Math.floor(-1.0789 * 100) / 100` returns `-1.08`. For rounding toward zero, you have to branch: `result = value < 0 ? Math.ceil(value) : Math.floor(value)`. – T.J. Crowder Nov 28 '22 at 09:55
  • I found an example that breaks the original solution: `console.log(4222.11 * 100);` is `422210.99999999994` so it incorrectly returns `4222.10` but the exponential notation method avoids this bug. – J Davies Jan 03 '23 at 15:45
1

you have several methods for do this

  1. Use Math.round(num * 100) / 100
  2. Use Math.ceil(num * 100)/100;
ADH - THE TECHIE GUY
  • 4,125
  • 3
  • 31
  • 54