This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 6 years ago.
I have a script where I pass it a string, and it'll return that string formatted as dollars. So if I send it "10000" it'll return "$10,000.00" Now the problem is that when I send it "1000000" ($1 million) it returns "$1,000.00" because it's only setup to parse based on one set of zeros. Here's my script, how can I adjust it to account for two sets of zeros ($1 million) ??
String.prototype.formatMoney = function(places, symbol, thousand, decimal) {
if((this).match(/^\$/) && (this).indexOf(',') != -1 && (this).indexOf('.') != -1) {
return this;
}
places = !isNaN(places = Math.abs(places)) ? places : 2;
symbol = symbol !== undefined ? symbol : "$";
thousand = thousand || ",";
decimal = decimal || ".";
var number = Number(((this).replace('$','')).replace(',','')),
negative = number < 0 ? "-" : "",
i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return negative + symbol + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : ""); };
Thanks in advance for any useful information!
function formatMoney(number) {
return number.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
}
console.log(formatMoney(10000)); // $10,000.00
console.log(formatMoney(1000000)); // $1,000,000.00
Give this a shot it looks for a decimal separator but you can remove that part if youd like:
{
number = parseFloat(number);
//if number is any one of the following then set it to 0 and return
if (isNaN(number)) {
return ('0' + '{!decimalSeparator}' + '00');
}
number = Math.round(number * 100) / 100; //number rounded to 2 decimal places
var numberString = number.toString();
numberString = numberString.replace('.', '{!decimalSeparator}');
var loc = numberString.lastIndexOf('{!decimalSeparator}'); //getting position of decimal seperator
if (loc != -1 && numberString.length - 2 == loc) {
//Adding one 0 to number if it has only one digit after decimal
numberString += '0';
} else if (loc == -1 || loc == 0) {
//Adding a decimal seperator and two 00 if the number does not have a decimal separator
numberString += '{!decimalSeparator}' + '00';
}
loc = numberString.lastIndexOf('{!decimalSeparator}'); //getting position of decimal seperator id it is changed after adding 0
var newNum = numberString.substr(loc, 3);
// Logic to add thousands seperator after every 3 digits
var count = 0;
for (var i = loc - 1; i >= 0; i--) {
if (count != 0 && count % 3 == 0) {
newNum = numberString.substr(i, 1) + '{!thousandSeparator}' + newNum;
} else {
newNum = numberString.substr(i, 1) + newNum;
}
count++;
}
// return newNum if youd like
};
Related
I am completely new to Javascript and trying to solve a simple problem now for more than two weeks and still not getting it(please help).
TASK ::::
Read a 4 digit Number e.g. 5678
Write a function
Split/separate the numbers and than build (5678, 567, 56, 5), than check if the numbers(5678, 567, 56, 5) are Prime numbers.
Give in Console/Result if 5678 a prime number or not, 567 a prime number or not and so on.
Check "if all numbers are Prime" than show result "All prime" if not show result "Not all prime".
Trying to solve the problem with (if else) but not really getting it, because i know very less about Javascript (arrays, string, split, slice) yet.
please help me understand. Thanks.
var a = 123456789;
var b = a.toString().length; //<<--->> ANTWORT: 9
document.write('ANTWORT: ',a );
for (i=0; i<b; i++) {
var x = a.toString().slice(0, -i);
document.write(x, ",");
}
function isPrime{
for(var i = 2; i < a; i++);
if(num % i === 0) return false;
return num > 1;
}
//integer is a string at the moment
integer = prompt("Enter a integer: ");
//initialize array for dictionary
dictArray = [];
stuff = document.getElementById("stuff");
//loop through all values of the string
for (var i = integer.length; i > 0; i--)
{
//take a substring from 0 to the ith char and turn it into an int
num = parseInt(integer.substring(0, i));
//add a dictionary to the array the tells what the number is
//and if it was prime or not as a bool
dictArray.push({"num": num, "prime": isprime(num)});
(dictArray[integer.length - i]["prime"]) ? stuff.innerHTML += "<br>" + num + " is prime." : stuff.innerHTML += "<br>" + num + " is not prime.";
}
function isprime(num)
{
if (num <= 3) return num >= 1;
if ((num % 2 === 0) || (num % 3 === 0)) return false;
let count = 5;
while (Math.pow(count, 2) <= num) {
if (num % count === 0 || num % (count + 2) === 0) return false;
count += 6;
}
return true;
}
//print the array
(dictArray.find(x => !x.prime) == undefined) ? stuff.innerHTML += "<br>All prime!" : stuff.innerHTML += "<br>Not all prime!";
//console.log(dictArray);
<div id="stuff">
</div>
I am using javascript to format the number with commas , it was working very fine.
But now the problem is if a value is comming in negative for example : -792004
It is returning the output like : -,792,004 that is comma is in the start.
How can I modify this method ?
Here is my code :
function Comma(number) {
number = '' + number;
if (number.length > 3) {
var mod = number.length % 3;
var output = (mod > 0 ? (number.substring(0, mod)) : '');
for (i = 0; i < Math.floor(number.length / 3); i++) {
if ((mod == 0) && (i == 0))
output += number.substring(mod + 3 * i, mod + 3 * i + 3);
else
output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
}
return (output);
} else return number;
}
The simplest way I know which will helps you is toLocaleString() method on number:
var x = 10033001;
var y = -10033001;
console.log(x.toLocaleString(), y.toLocaleString());
But for correction of your code, you can remove number sign with Math.abs and add it after with Math.sign.
var sign = Math.sign(number);
number = Math.abs(number);
// Do the conversion
return (sign < 0) ? ("-" + output) : output;
Try this:
const comma = function(number) {
const prefix = number < 0 ? '-' : ''
number = String(Math.abs(number))
if (number.length > 3) {
const mod = number.length % 3
let output = (mod > 0 ? (number.substring(0,mod)) : '')
for (let i = 0; i < Math.floor(number.length / 3); i++) {
if (mod === 0 && i === 0)
output += number.substring(mod+ 3 * i, mod + 3 * i + 3)
else
output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
}
return prefix + output
} else {
return prefix + number
}
}
If the number is negative, it assigns - to prefix. Then it changes number to its absolute value (Math.abs(number)). In the end it returns value with prefix.
I'm programming a method in JavaScript/JQuery which converts the value an user enters in an inputbox. The meaning is to make this input regional aware.
The functionality contains removing zeros at the beginning, placing thousand seperators and a decimal separator.
In this use case is the , symbol a thousand separator and the . dot the decimal separator
For example following input gets converted in following output.
12300 => 12,300.00
100 => 100.00
1023.456 => 1,023.456
Now There is still a problem with numbers, less than 100.
For example following input is malformed:
1 => 1,.00
2.05 => .05
20 => 20,.00
25.65 => .65
When I don't enter a decimal value in the input box, I get an unneeded thousand separator. When I enter a decimal value, I lose my content before the decimal separator.
The code:
$("#queryInstructedAmountFrom").change(function(){
var amount = $("#queryInstructedAmountFrom").val();
amount = removeZeros(amount);
var nonFractions = amount.match(/.{1,3}/g);
if(nonFractions == null) {
nonFractions = [];
nonFractions.push(amount);
}
var splittedValues = amount.split(/[,.]/);
amount = "";
if(splittedValues.length == 1) {
amount += splittedValues[0];
nonFractions = amount.match(/.{1,3}/g);
var firstIndex = amount.length % 3;
if(firstIndex != 0) {
var firstNumbers = amount.substr(0, firstIndex);
amount = amount.substr(firstIndex);
nonFractions = amount.match(/.{1,3}/g);
if(nonFractions == null) {
nonFractions = [];
nonFractions.push(amount);
}
amount = "";
amount += firstNumbers;
amount += thousandSeparator;
} else {
amount = "";
}
for(var i=0 ; i < nonFractions.length ; i++) {
amount += nonFractions[i];
if(i < (nonFractions.length - 1) && nonFractions.length != 1){
amount += thousandSeparator;
}
}
amount += decimalSeparator;
amount += "00";
} else {
for(var i=0 ; i < splittedValues.length - 1 ; i++) {
amount += splittedValues[i];
}
nonFractions = amount.match(/.{1,3}/g);
var firstIndex = amount.length % 3;
if(firstIndex == 0) {
nonFractions = amount.match(/.{1,3}/g);
}
if(firstIndex >= 1 && nonFractions != null) {
var firstNumbers = amount.substr(0, firstIndex);
amount = amount.substr(firstIndex);
nonFractions = amount.match(/.{1,3}/g);
if(nonFractions != null) {
amount = "";
amount += firstNumbers;
amount += thousandSeparator;
} else {
nonFractions = [];
nonFractions.push(amount);
}
} else {
amount = "";
}
for(var i=0 ; i < nonFractions.length ; i++) {
amount += nonFractions[i];
if(i < (nonFractions.length - 1) && nonFractions.length != 1){
amount += thousandSeparator;
}
}
amount += decimalSeparator;
amount += splittedValues[splittedValues.length -1];
}
$("#queryInstructedAmountFrom").val(amount);
});
});
function removeZeros(amount) {
while (amount.charAt(0) === '0') {
amount = amount.substr(1);
}
if(amount.length == 0){
amount = "0";
}
return amount;
}
What is going wrong?
What is going wrong?
I'd say almost everything. You have very unclear, messy code, I hardly following your logic, but you have several critical logic mistakes in code, for example:
1
1 is converted to 1,.00 because:
var splittedValues = amount.split(/[,.]/);
creates array with single element ['1']
var firstIndex = amount.length % 3;
1%3 == 1, so you're going into if condition, where amount += thousandSeparator; appends thousand separator, but you should add separator only if you have something after that
2
2.05 is wrong, because it goes into this branch:
var firstNumbers = amount.substr(0, firstIndex); // stores '2' into firstNumbers
amount = amount.substr(firstIndex); // sets amount to empty string
later, nonFractions is null:
nonFractions = [];
nonFractions.push(amount);
but firstNumbers is not used at all, ie its value is lost
3
also, you have:
nonFractions = amount.match(/.{1,3}/g);
var firstIndex = amount.length % 3;
if (firstIndex == 0) {
nonFractions = amount.match(/.{1,3}/g);
}
what is the sense of nonFractions re-init?
probably there are more errors and edge cases where this code fails, I suggest you to use library (like in other answers) or if you want to have your own code, here is simple version you can use:
$(document).ready(function() {
$("#queryInstructedAmountFrom").change(function() {
var val = parseFloat(('0' + $("#queryInstructedAmountFrom").val()).replace(/,/g, '')); // convert original text value into float
val = ('' + (Math.round(val * 100.0) / 100.0)).split('.', 2);
if (val.length < 2) val[1] = '00'; // handle fractional part
else while (val[1].length < 2) val[1] += '0';
var t = 0;
while ((val[0].length - t) > 3) { // append thousand separators
val[0] = val[0].substr(0, val[0].length - t - 3) + ',' + val[0].substr(val[0].length - t - 3);
t += 4;
}
$("#queryInstructedAmountFrom").val(val[0] + '.' + val[1]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="queryInstructedAmountFrom">
Why don't you use jQuery-Mask-Plugin?
<input type="text" id="money" />
and just invoke the plugin:
$('#money').mask('000.000.000.000.000,00', {reverse: true});
Plunker: https://plnkr.co/edit/PY7ihpS3Amtzeya9c6KN?p=preview
Refer to the below code updated.
$(document).ready(function() {
$("#queryInstructedAmountFrom").change(function() {
var amount = $("#queryInstructedAmountFrom").val();
amount = removeZeros(amount);
// format amount using 'ThousandFormattedValue' function
amount = ThousandFormattedValue(amount);
$("#queryInstructedAmountFrom").val(amount);
});
});
function removeZeros(amount) {
while (amount.charAt(0) === '0') {
amount = amount.substr(1);
}
if (amount.length == 0) {
amount = "0";
}
return amount;
}
function ThousandFormattedValue(iValue) {
// declaring variables and initializing the values
var numberArray, integerPart, reversedInteger, IntegerConstruction = "",
lengthOfInteger, iStart = 0;
// splitting number at decimal point by converting the number to string
numberArray = iValue.toString().split(".");
// get the integer part
integerPart = numberArray[0];
// get the length of the number
lengthOfInteger = integerPart.length;
// if no decimal part is present then add 00 after decimal point
if (numberArray[1] === undefined) {
numberArray.push("00");
}
/* split the integer part of number to individual digits and reverse the number
["4" , "3" , "2" , "1"] - after split
["1" , "2" , "3" , "4"] - after reverse
"1234" - after join
*/
reversedInteger = integerPart.split("").reverse().join("");
// loop through the string to add commas in between
while (iStart + 3 < lengthOfInteger) {
// get substring of very 3 digits and add "," at the end
IntegerConstruction += (reversedInteger.substr(iStart, 3) + ",");
// increase counter for next 3 digits
iStart += 3;
}
// after adding the commas add the remaining digits
IntegerConstruction += reversedInteger.substr(iStart, 3);
/* now split the constructed string and reverse the array followed by joining to get the formatted number
["1" , "2" , "3" , "," ,"4"] - after split
["4" , "," , "3" , "2" , "1"] - after reverse
"4,321" - after join
*/
numberArray[0] = IntegerConstruction.split("").reverse().join("");
// return the string as Integer part concatinated with decimal part
return numberArray.join(".");
}
I need to increment a value similar to this:
A001 becomes A002
A999 becomes B001
B001 becomes B002
etc
Z999 becomes A001
I can increment an integer like this:
var x = 5;
x++;
Yields x = 6
I can increment an character like this:
var str = 'A';
str = ((parseInt(str, 36)+1).toString(36)).replace(/0/g,'A').toUpperCase();
if (str =='1A') {
str = 'A';
}
Yields the next character in the alphabet.
This code seems to work, but I'm not sure it's the best way?
var str = 'Z999';
if (str == 'Z999') {
results = 'A001';
}
else {
var alpha = str.substring(0,1);
num = str.substring(1,4);
if (alpha != 'Z' && num == '999') {
alpha= ((parseInt(alpha, 36)+1).toString(36)).replace(/0/g,'A').toUpperCase();
}
num++;
var numstr = num + "";
while (numstr .length < 3) numstr = "0" + numstr ;
if (numstr == 1000) {
numstr = '001';
}
results = alpha + numstr;
}
results seems to give the correct answer. Yes?
You could use parseInt(input.match(/\d+$/), 10) to extract the number at the end of the string and input.match(/^[A-Za-z]/) to retreive the single character at the beginning.
Increment and pad the number accordingly, and increment the character if the number is over 999 by retrieving the character's character code and incrementing that.
String.fromCharCode(letter.charCodeAt(0) + 1);
Full code/example:
function incrementNumberInString(input) {
var number = parseInt(input.trim().match(/\d+$/), 10),
letter = input.trim().match(/^[A-Za-z]/)[0];
if (number >= 999) {
number = 1;
letter = String.fromCharCode(letter.charCodeAt(0) + 1);
letter = letter === '[' ? 'A': (letter === '{' ? 'a' : letter);
} else {
number++;
}
number = '000'.substring(0, '000'.length - number.toString().length) + number;
return letter + number.toString();
}
document.querySelector('pre').textContent =
'A001: ' + incrementNumberInString('A001')
+ '\nA999: ' + incrementNumberInString('A999')
+ '\nB001: ' + incrementNumberInString('B001')
+ '\nB044: ' + incrementNumberInString('B044')
+ '\nZ999: ' + incrementNumberInString('Z999');
<pre></pre>
Output:
A001: A002
A999: B001
B001: B002
B044: B045
D7777: E001
Try storing A-Z in an array , using String.prototype.replace() with RegExp /([A-Z])(\d+)/g to match uppercase characters , digit characters . Not certain what expected result is if "Z999" reached ?
var arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
var spans = document.querySelectorAll("span");
function count(el) {
var data = el.innerHTML.replace(/([A-Z])(\d+)/g, function(match, text, n) {
var _text, _n;
if (Number(n) === 999) {
_text = arr[ arr.indexOf(text) + 1 ];
} else {
_text = text
};
// `"Z999"` condition ?
if (_text === undefined) {
return "<mark>" + text + n + "</mark>"
}
_n = Number(n) + 1 < 1000 ? Number(n) + 1 : "001";
if (n < 10) {
return _text + n.slice(0, 2) + _n
};
if (n < 100) {
return _text + n.slice(0, 1) + _n
} else {
return _text + _n
}
});
el.innerHTML = data
}
for (var i = 0; i < spans.length; i++) {
count(spans[i])
}
<span>A001</span>
<span>A999</span>
<span>B001</span>
<span>C999</span>
<span>D123</span>
<span>Z999</span>
a script returns either a number like 0.0580 so in x.xxxx format or a (x) for X units left.
I want to format the number 0.0580 and return 5.8 cent or return x units left.
Any ideas how to do that in javascript? Especially how do I format the x.xxxx?
In case the first x is not 0 I want to return e.g. 1.75$.
MS has written a nice plugin for jquery. it's especially useful if you're localizing. Give it a go:
http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx
I'm not sure if this can be used outside of jquery...
I may be spoiling you here, but whatever. Here's a function that I found somewhere at some point and have been recycling since. I haven't actually bothered to look much into it to figure out what it does exactly, but it has been rather useful:
function FormatMoneyAmount(starting_string, ending_string) {
//check validity of input (true = invalid, false = valid)
var valid_exp = new RegExp ('[^0-9,.$]', 'gi');
input_invalid = (typeof(ending_string) == 'undefined' && valid_exp.test(starting_string));
//check if more than 2 digits follow decimal or no decimal
decimal_invalid = typeof(ending_string) == 'undefined' && (starting_string.indexOf('.') > -1) && ((starting_string.length - starting_string.indexOf('.')) > 3);
if (input_invalid || decimal_invalid) {
ending_string = starting_string;
} else {
//remove commas, dollar signs
var replace_exp = new RegExp ('[,$]', 'gi');
starting_string = starting_string.replace(replace_exp, '');
//remove decimal if ending string not set, save for adding on later
var decimal_substring = '';
if (typeof(ending_string) == 'undefined' && starting_string.indexOf('.') > -1) {
decimal_substring = starting_string.substring(starting_string.indexOf('.'), starting_string.length);
remaining_string = starting_string.substring(0,starting_string.indexOf('.'));
} else {
remaining_string = starting_string;
}
//if string is already 3 characters or less, do nothing
if (remaining_string.length > 3) {
//separate last 3 characters of string from rest of string
var final_three = remaining_string.substring(remaining_string.length - 3, remaining_string.length);
remaining_string = remaining_string.substring(0, remaining_string.length - 3);
//if not first group of 3, add new group before old group with comma, else set to new group
ending_string = (typeof(ending_string) == 'undefined') ? final_three + ((typeof(decimal_substring) == 'undefined') ? '' : decimal_substring) : final_three + ',' + ending_string;
//call function again if more than 3 digits remaining to process, else add to end string
if (remaining_string.length > 3) {
ending_string = FormatMoneyAmount(remaining_string, ending_string);
} else {
ending_string = remaining_string + ',' + ending_string;
}
} else {
ending_string = (typeof(ending_string) == 'undefined') ? remaining_string : remaining_string + ',' + ending_string + ((typeof(decimal_substring) == 'undefined') ? '' : decimal_substring);
}
}
return ending_string;
}
The first thing to do is check the format of the string, since you will have two code paths depending on the result:
if (typeof num = "string" && num.slice(0,1) == "(" && num.slice(-1) == ")") {
// String is in the format (x), so we just need to return that number
return num.slice(1,-1) + " units left";
}
The next part is to check if the number is less than 1, indicating that it is cents and not whole dollars. If it is less than 1, multiplying it by 100 will give you the number of cents you're after:
if (+num < 1)
// 0.0580 * 100 = 5.8
return (num * 100) + " cents";
else
return +num + "$";