4

I would format a number with 2 decimal places without rounding. So I excluded the toFixed() function.

I have tried this way

a = 1,809999
b = 27,94989

a = Math.floor(a * 100) / 100; --> 1,8
b = Math.floor(b * 100) / 100; --> 27,94

OR

a = Number(a.toString().match(/^\d+(?:\.\d{0,2})?/)); --> 1,8
b = Number(b.toString().match(/^\d+(?:\.\d{0,2})?/)); --> 27,94

Unfortunately, the second decimal of a is zero, and this was deleted, how could I do to keep it and have a = 1.80? Thank you

Gus
  • 913
  • 2
  • 15
  • 30

5 Answers5

4
(Math.floor(a * 100) / 100).toFixed(2);

With toFixed(2) !

JSFIDDLE DEMO

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
Enjoyted
  • 1,131
  • 6
  • 15
1

You can try like this:

a= a.toString().slice(0, (a.indexOf("."))+3); 

JSFIDDLE DEMO

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • You forgot second `a` is number in yours oneliner. Solution `a = a.toString(); a.slice(0, (a.indexOf("."))+3); ` or `a = a.toString().slice(0, (a.toString().indexOf("."))+3); ` – user3439968 Apr 12 '19 at 21:58
0

Rounding a number is about changing it's value, and should be done with math operations (Math.floor, Math.ceil, Math.round, ...).

Formatting number, is about how do numbers get displayed to a human user (like Date formatting).

Javascript does not comes with acceptable native tool to do number formatting.

You can always play with rounding to make javascript print a number the way you want, but you will end up writing a lot of (possibly buggy) code.

I would recommend using a library to format your numbers http://numeraljs.com/

numeral(number).format('0.00');
Eloims
  • 5,106
  • 4
  • 25
  • 41
0

only need to use toFixed() and pass number like 2 then it show after . two decimal like bello

a = 1,809999
b = 27,94989

a = Math.floor(a * 100) / 100; 
b = Math.floor(b * 100) / 100; 

$(".testa").text(a.toFixed(2)); //see here.
$(".testb").text(b.toFixed(2)); //see here.

Html :

<div class="testa"></div>
<br>
    <div class="testb"></div>

i hope this will help you. and also see this jsfiddle link http://jsfiddle.net/RGerb/394/

lalitpatadiya
  • 720
  • 7
  • 21
0
myFunction(value: number){
let x = value + ''; 
  var a =  x.lastIndexOf('.')>=0?parseFloat(x.substr(0,x.lastIndexOf('.')+(3))):value;
  var am = a.toFixed(2)
  console.log("Output: " + am);
  return am;

}

<button (click)="myFunction(656565.9668985)">My Function</button>

Output: 656565.96