I'm using the following script to use dots as the thousands separator and commas as decimals separator that I got from this question.
var numero = 1000.00;
function formatThousands(n, dp) {
var s = ''+(Math.floor(n)),
d = n % 1,
i = s.length,
r = '';
while ((i -= 3) > 0) {
r = '.' + s.substr(i, 3) + r;
}
return s.substr(0, i + 3) + r + (d ? ',' + Math.round(d * Math.pow(10,dp||2)) : '');
}
alert(formatThousands(numero,2));
/// http://jsperf.com/compare-two-format-thousands
See also jsfiddle
This is working OK, except for integers.
For example, the number 1000 will return 1.000 and I want it to return 1.000,00 since the numbers refer to Euro currency.
How can I add the 2 decimals (cents) in every number?
Thanks for helping!
Does this work?
function formatThousands(n, dp) {
var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
while ( (i -= 3) > 0 ) { r = '.' + s.substr(i, 3) + r; }
s = s.substr(0, i + 3) + r + (d ? ',' + Math.round(d * Math.pow(10,dp||2)) : '');
return s.charAt(-1) != ',' ? s+',00' : s;
}
EDIT:
How about this?
function formatThousands(n, dp) {
n = (''+n).split('.');
i = n[0];
d = !(n[1]) ? '00' : n[1];
n = i.match(/.{4}/g).join('.');
return n + ',' + d;
}
http://jsfiddle.net/XC3sS/12/
Related
can anyone come with an idea of how to sort an integer without using an array, and without using string methods as well as sort() method?
for example
input: 642531
output: 123456
I started by writing 2 simple functions - one which checks the length of the number, the other one splits the integer at some point and switches between 2 desired numbers. Below are the 2 functions.
I got stuck with the rest of the solution...
function switchDigits(num, i) { // for input: num=642531, i = 4 returns 624135
let temp = num;
let rest = 0;
for (let j = 0; j < i - 1; j++) {
rest = rest * 10;
rest = rest + temp % 10;
temp = (temp - temp % 10) / 10;
}
let a = temp % 10;
temp = (temp - a) / 10;
let b = temp % 10;
temp = (temp - b) / 10;
temp = Math.pow(10, i - 2) * temp;
temp = temp + 10 * a + b;
temp = Math.pow(10, i - 1) * temp;
temp = temp + rest;
return temp;
}
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
let num = 642534;
let i = checkHowManyDigits(num);
console.log(switchDigits(num));
It actually complicated requirement and so does this answer. It's pure logic and as it is it's a question from a test you should try understanding the logic on your own as a homework.
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
function sortDigit(numOriginal) {
let i = checkHowManyDigits(numOriginal);
let minCount = 0;
let min = 10;
let num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d < min) {
min = d;
minCount = 0;
} else if (d === min) {
minCount++;
}
}
let result = 0;
while (minCount >= 0) {
result += min * Math.pow(10, i - minCount - 1);
minCount--;
}
let newNum = 0;
num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d !== min) {
newNum = newNum * 10 + d;
}
}
if (newNum == 0) return result;
else return result += sortDigit(newNum);
}
console.log(sortDigit(642531));
You could have a look to greater and smaller pairs, like
64
46
The delta is 18, which gets an idea if you compare other pairs, like
71
17
where the delta is 54. Basically any difference of two digits is a multiple of 9.
This in mind, you get a function for taking a single digit out of a number and a single loop who is sorting the digits by using the calculated delta and subtract the value, adjusted by the place.
function sort(number) {
const
getDigit = e => Math.floor(number / 10 ** e) % 10,
l = Math.ceil(Math.log10(number)) - 1;
let e = l;
while (e--) {
const
left = getDigit(e + 1),
right = getDigit(e);
if (left <= right) continue;
number += (right - left) * 9 * 10 ** e;
e = l;
}
return number;
}
console.log(sort(17)); // 17
console.log(sort(71)); // 17
console.log(sort(642531)); // 123456
console.log(sort(987123654)); // 123456789
So eventually I found the best solution.
*This solution is based on a Java solution I found in StackOverFlow forums.
let store = 0;
function getReducedNumbr(number, digit) {
console.log("Remove " + digit + " from " + number);
let newNumber = 0;
let repeateFlag = false;
while (number>0) {
let t = number % 10;
if (t !== digit) {
newNumber = (newNumber * 10) + t;
} else if (t == digit) {
if (repeateFlag) {
console.log(("Repeated min digit " + t + " found. Store is : " + store));
store = (store * 10) + t;
console.log("Repeated min digit " + t + " added to store. Updated store is : " + store);
} else {
repeateFlag = true;
}
}
number = Math.floor(number / 10);
}
console.log("Reduced number is : " + newNumber);
return newNumber;}
function sortNum(num) {
let number = num;
let original = number;
let digit;
while (number > 0) {
digit = number % 10;
console.log("Last digit is : " + digit + " of number : " + number);
temp = Math.floor(number/10);
while (temp > 0) {
console.log("subchunk is " + temp);
t = temp % 10;
if (t < digit) {
digit = t;
}
temp = Math.floor(temp/10);
}
console.log("Smallest digit in " + number + " is " + digit);
store = (store * 10) + digit;
console.log("store is : " + store);
number = getReducedNumbr(number, digit);
}
console.log(("Ascending order of " + original + " is " + store));
return store;
}
console.log(sortNum(4214173));
you can see how it works here https://jsfiddle.net/9dpm14fL/1/
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 am trying to print a number with two decimal places, and I need it with dots as thousands separators.
I can't use .toLocaleString(), since it won't work in Safari...
Here's my code:
var currentTime;
if (localStorage['time']) {
currentTime = Number.parseFloat(localStorage['time']);
}
else {
currentTime = 0;
}
var container = document.getElementById('count');
setInterval(function() {
currentTime += .01;
container.innerHTML = currentTime.toFixed(2);
//container.innerHTML = currentTime.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
localStorage['time'] = currentTime;
}, 100);
You can use this snippet which works in most cases:
// source: http://stackoverflow.com/a/149099/280842
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
use it as:
(123456789.12345).formatMoney(2, '.', ',');
Working example: https://jsbin.com/nuyinatuju/edit?js,console
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>
How to Get number with 2 decimal and not rounding using javascript ?
i try
http://jsfiddle.net/3AaAx/31/
var i = "1234.666";
var xxx = Math.floor(i * 100) / 100
alert(xxx);
AND
http://jsfiddle.net/3AaAx/29/
var i = "1234.666";
function myToFixed(i, digits) {
var pow = Math.pow(10, digits);
return Math.floor(i * pow) / pow;
}
var xxx = myToFixed(i, 2)
alert(xxx);
it's work.
But when i declare var i = "1234"; i want to get "1234.00"
http://jsfiddle.net/3AaAx/30/
http://jsfiddle.net/3AaAx/32/
How to do that ?
Not rounding is an unusual requirement, and it's too bad because if you were okay with rounding, you could just use toFixed:
var num = 1234.5678;
snippet.log(num.toFixed(2)); // "1234.57" -- note the rounding!
var num = 1234.5678;
snippet.log(num.toFixed(2)); // "1234.57" -- note the rounding!
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
(And no, you can't just do .toFixed(3) and then chop off the last digit; rounding doesn't necessarily only change the last digit, consider using toFixed(3) on 1111.9999, which gives you 1112.000. Just chopping off the last digit of that still gives you a rounded result.)
To do it without rounding, I don't think there's much available but brute force:
// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
var parts = String(num).split('.');
if (digits <= 0) {
return parts[0];
}
var fractional = (parts[1] || "0") + "000000000000000000000";
return parts[0] + "." + fractional.substring(0, digits);
}
// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
var parts = String(num).split('.');
if (digits <= 0) {
return parts[0];
}
var fractional = (parts[1] || "0") + "000000000000000000000";
return parts[0] + "." + fractional.substring(0, digits);
}
var num, notRounded;
num = 1234;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.5678;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.1;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.999999;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Or you can use indexOf, but it seems a lot clunkier:
// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
var str = String(num);
var n = str.indexOf(".") + 1;
if (n === 0) {
str += ".";
n = str.length;
}
n = digits <= 0 ? n - 1 : n + digits;
if (str.length !== n) {
str = (str + "00000000000000000000").substring(0, n);
}
return str;
}
// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
var str = String(num);
var n = str.indexOf(".") + 1;
if (n === 0) {
str += ".";
n = str.length;
}
n = digits <= 0 ? n - 1 : n + digits;
if (str.length !== n) {
str = (str + "00000000000000000000").substring(0, n);
}
return str;
}
var num, notRounded;
num = 1234;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.5678;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.1;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.999999;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
var y = "1234.045";
var s = number_with_2_decimal(y);
alert(s);
function number_with_2_decimal(a) {
var x = Math.floor(a * 100) * 0.01;
var str = String(x);
var n = str.indexOf('.');
if (n === -1) {
str += '.00';
};
return str;
}