How to Format a Float in JavaScript

How to format a float in javascript?

var result = Math.round(original*100)/100;

The specifics, in case the code isn't self-explanatory.

edit: ...or just use toFixed, as proposed by Tim Büthe. Forgot that one, thanks (and an upvote) for reminder :)

Javascript format float number

For numbers 0 - 1000:

function format( num ){
return ( Math.floor(num * 1000)/1000 ) // slice decimal digits after the 2nd one
.toFixed(2) // format with two decimal places
.substr(0,4) // get the leading four characters
.replace(/\.$/,''); // remove trailing decimal place separator
}

// > format(0)
// "0.00"
// > format(1.3456)
// "1.34"
// > format(12)
// "12.0"
// > format(529.96)
// "529"

Now for numbers 1000 - 999 999 you need to divide them by a 1000 and append "K"

function format( num ){
var postfix = '';
if( num > 999 ){
postfix = "K";
num = Math.floor(num / 1000);
}
return ( Math.floor(num * 1000)/1000 )
.toFixed(2)
.substr(0,4)
.replace(/\.$/,'') + postfix;
}
// results are the same for 0-999, then for >999:
// > format(12385.123)
// "12.3K"
// > format(1001)
// "1.00K"
// > format(809888)
// "809K"

If you need to format 1 000 000 as 1.00M then you can add another condition with "M" postfix etc.

Edit: demo up to Trillions: http://jsfiddle.net/hvh0w9yp/1/

How to format numbers as currency strings

Ok, based on what you said, I'm using this:

var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1);

var AmountWithCommas = Amount.toLocaleString();
var arParts = String(AmountWithCommas).split(DecimalSeparator);
var intPart = arParts[0];
var decPart = (arParts.length > 1 ? arParts[1] : '');
decPart = (decPart + '00').substr(0,2);

return '£ ' + intPart + DecimalSeparator + decPart;

I'm open to improvement suggestions (I'd prefer not to include YUI just to do this :-) )

I already know I should be detecting the "." instead of just using it as the decimal separator...

JavaScript displaying a float to 2 decimal places

float_num.toFixed(2);

Note:toFixed() will round or pad with zeros if necessary to meet the specified length.

Formatting a number with exactly two decimals in JavaScript

To format a number using fixed-point notation, you can simply use the toFixed method:

(10.8).toFixed(2); // "10.80"

var num = 2.4;
alert(num.toFixed(2)); // "2.40"

Note that toFixed() returns a string.

IMPORTANT: Note that toFixed does not round 90% of the time, it will return the rounded value, but for many cases, it doesn't work.

For instance:

2.005.toFixed(2) === "2.00"

UPDATE:

Nowadays, you can use the Intl.NumberFormat constructor. It's part of the ECMAScript Internationalization API Specification (ECMA402). It has pretty good browser support, including even IE11, and it is fully supported in Node.js.

const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});

console.log(formatter.format(2.005)); // "2.01"
console.log(formatter.format(1.345)); // "1.35"

How to format a float as integer when .toFixed(2) gives zeros after the decimal point?

...preferrably without parsing and manipulating the string that comes out of .toFixed(2)?

Well, you could do it numerically, though I'd worry about getting a perfect match between numeric logic and toFixed's logic, given the definition of toFixed includes phrases like:

Let n be an integer for which the exact mathematical value of n ÷ 10f - x is as close to zero as possible. If there are two such n, pick the larger n.

So I'd probably just update the string, it's not a lot of work:

function formatNumber(num) {    return num.toFixed(2).replace(/\.00$/, "");}
function test(num) { console.log(num, "=>", formatNumber(num));}test(1.01);test(1.43);test(23.7);test(1.200123);test(1.000043);test(1.007);test(1.0007);

Format number to always show 2 decimal places

(Math.round(num * 100) / 100).toFixed(2);

Live Demo

var num1 = "1";document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2);
var num2 = "1.341";document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);
var num3 = "1.345";document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);
span {    border: 1px solid #000;    margin: 5px;    padding: 5px;}
<span id="num1"></span><span id="num2"></span><span id="num3"></span>

How to format a float to two digit

if you want to format a float to any number of digits use this function:

function truncate(num, pos) {

return Math.floor(num*Math.pow(10, pos))/Math.pow(10, pos);

}

where num is the float and pos is the number of digits you want after the decimal.

Javascript format number of decimal places in float

As a float 8.50 an 8.5 are identical. However when you convert your number to a string you can specify the number of decimal places you would like to use with the function toFixed() e.g.

var a = parseFloat($("#salaryFrom").val());
var b = a.toFixed(2);

The function toFixed() takes the number of decimal places you would like to format your number to, in this case 2.

How do I convert a float number to a whole number in JavaScript?

var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue );
var intvalue = Math.round( floatvalue );

// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );

Math object reference



Examples

Positive
// value=x        //  x=5          5<x<5.5      5.5<=x<6  

Math.floor(value) // 5 5 5
Math.ceil(value) // 5 6 6
Math.round(value) // 5 5 6
Math.trunc(value) // 5 5 5
parseInt(value) // 5 5 5
~~value // 5 5 5
value | 0 // 5 5 5
value >> 0 // 5 5 5
value >>> 0 // 5 5 5
value - value % 1 // 5 5 5
Negative
// value=x        // x=-5         -5>x>=-5.5   -5.5>x>-6

Math.floor(value) // -5 -6 -6
Math.ceil(value) // -5 -5 -5
Math.round(value) // -5 -5 -6
Math.trunc(value) // -5 -5 -5
parseInt(value) // -5 -5 -5
value | 0 // -5 -5 -5
~~value // -5 -5 -5
value >> 0 // -5 -5 -5
value >>> 0 // 4294967291 4294967291 4294967291
value - value % 1 // -5 -5 -5
Positive - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1

// value=x x=900719925474099 x=900719925474099.4 x=900719925474099.5

Math.floor(value) // 900719925474099 900719925474099 900719925474099
Math.ceil(value) // 900719925474099 900719925474100 900719925474100
Math.round(value) // 900719925474099 900719925474099 900719925474100
Math.trunc(value) // 900719925474099 900719925474099 900719925474099
parseInt(value) // 900719925474099 900719925474099 900719925474099
value | 0 // 858993459 858993459 858993459
~~value // 858993459 858993459 858993459
value >> 0 // 858993459 858993459 858993459
value >>> 0 // 858993459 858993459 858993459
value - value % 1 // 900719925474099 900719925474099 900719925474099
Negative - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1

// value = x // x=-900719925474099 x=-900719925474099.5 x=-900719925474099.6

Math.floor(value) // -900719925474099 -900719925474100 -900719925474100
Math.ceil(value) // -900719925474099 -900719925474099 -900719925474099
Math.round(value) // -900719925474099 -900719925474099 -900719925474100
Math.trunc(value) // -900719925474099 -900719925474099 -900719925474099
parseInt(value) // -900719925474099 -900719925474099 -900719925474099
value | 0 // -858993459 -858993459 -858993459
~~value // -858993459 -858993459 -858993459
value >> 0 // -858993459 -858993459 -858993459
value >>> 0 // 3435973837 3435973837 3435973837
value - value % 1 // -900719925474099 -900719925474099 -900719925474099


Related Topics



Leave a reply



Submit