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);
Add .00 (toFixed) only if number has less than two decimal places
Here you go:
function addZeroes(num) {
// Convert input string to a number and store as a variable.
var value = Number(num);
// Split the input string into two arrays containing integers/decimals
var res = num.split(".");
// If there is no decimal point or only one decimal place found.
if(res.length == 1 || res[1].length < 3) {
// Set the number to two decimal places
value = value.toFixed(2);
}
// Return updated or original number.
return value;
}
// If you require the number as a string simply cast back as so
var num = String(value);
See fiddle for demonstration.
edit: Since I first answered this, javascript and I have progressed, here is an improved solution using ES6, but following the same idea:
function addZeroes(num) {
const dec = num.split('.')[1]
const len = dec && dec.length > 2 ? dec.length : 2
return Number(num).toFixed(len)
}
Updated fiddle
edit 2: Or if you are using optional chaining you can do it in one line like so:
const addZeroes = num => Number(num).toFixed(Math.max(num.split('.')[1]?.length, 2) || 2)
Updateder fiddle
How to parse float with two decimal places in javascript?
You can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)
Truncate number to two decimal places without rounding
Convert the number into a string, match the number up to the second decimal place:
function calc(theform) { var num = theform.original.value, rounded = theform.rounded var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0] rounded.value = with2Decimals}
<form onsubmit="return calc(this)">Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" /><br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly></form>
add trailing zeroes if a number is an integer in TypeScript
You are probably looking for toFixed
:
console.log((9.01111).toFixed(2)); // 9.01
console.log((9.01).toFixed(2)); // 9.01
console.log((9).toFixed(2)); // 9.00
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 :)
Related Topics
Filter Input Text to Enter Only Number and Not Even Decimal
How to Mock the JavaScript Window Object Using Jest
How to Attach Multiple Images in a Embed
Whenever I Click Outside the Element It Should Close
Angular: How to Get Default @Input Value
Nodejs MySQL Get Correct Timestamp Format
Label and Input Fields on the Same Line
Get Part of the Url Pathname Via JavaScript Regex
How to Reduce Vendor/Script Bundle.Js in Angular 5
Javascript: How to Read a Hand Held Barcode Scanner Best
Making a JavaScript Function That Finds the First Word in a String/Sentence
How to Remove Captcha Verification from Firebase Phone Auth Using JavaScript
Expand Div on Click With Smooth Animation
How to Reference Static Assets Within Vue JavaScript
Angular 4 | Window.Scrollto(); Is Not Working Properly
How to Modify Chartjs Tooltip So I Can Add Customized Strings in Tooltips
Increase and Decrease Number With JavaScript and Two Buttons Up and Down
How to Iterate Using Ngfor Loop Map Containing Key as String and Values as Map Iteration