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...
How do I format a number in Java?
From this thread, there are different ways to do this:
double r = 5.1234;
System.out.println(r); // r is 5.1234
int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);
// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();
System.out.println(r); // r is 5.12
f = (float) (Math.round(n*100.0f)/100.0f);
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();
// The value of dd2dec will be 100.24
The DecimalFormat() seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.
How to format numbers to block of length three separated by comma, last 2 blocks or last block can be length of two but it cannot be length of one
I'm not sure that this is best way but n
is string so you can slice and you can count length
of string
function format(n) {
if((n.length - 6) % 2 === 0){ // is (n.length - 6) is divisible without remainder
return `${n.slice(0,3)}, ${n.slice(3,6)}, ${n.slice(6,8)}, ${n.slice(8,10)}`
}else{
return `${n.slice(0,3)}, ${n.slice(3,6)}, ${n.slice(6,9)}, ${n.slice(9,12)}`
}
}
console.log(format("0464356998"));
console.log(format("04643569981"));
How to print a number with commas as thousands separators in JavaScript
I used the idea from Kerry's answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I have:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
return pass;
}
let failures = 0;
failures += !test(0, "0");
failures += !test(100, "100");
failures += !test(1000, "1,000");
failures += !test(10000, "10,000");
failures += !test(100000, "100,000");
failures += !test(1000000, "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}
.as-console-wrapper {
max-height: 100% !important;
}
Related Topics
Iterate Through Nested JavaScript Objects
Split a String by Commas But Ignore Commas Within Double-Quotes Using JavaScript
Getting a Better Understanding of Callback Functions in JavaScript
Expression Inside Switch Case Statement
Execcommand() Is Now Obsolete, What's the Alternative
Sharing a Variable Between Multiple HTML Pages
Replace Innerhtml in Contenteditable Div
Capture Frames from Video with HTML5 and JavaScript
Get Caret Index in Contenteditable Div Including Tags
How to Download a File Using Window.Fetch
Add Event Listener on Elements Created Dynamically
How to Add Months to a Date in JavaScript
Difference Between HTMLcollection, Nodelists, and Arrays of Objects
Filter Array of Objects with Another Array of Objects
Get the Data of Uploaded File in JavaScript