Gus
Gus

Reputation: 943

JS - Format number with 2 decimal not rounded

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

Upvotes: 4

Views: 3208

Answers (5)

Amanur Rahman
Amanur Rahman

Reputation: 29

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

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

You can try like this:

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

JSFIDDLE DEMO

Upvotes: 1

Enjoyted
Enjoyted

Reputation: 1151

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

With toFixed(2) !

JSFIDDLE DEMO

Upvotes: 4

lalitpatadiya
lalitpatadiya

Reputation: 720

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/

Upvotes: 0

Eloims
Eloims

Reputation: 5224

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');

Upvotes: 0

Related Questions