How to divide a number into digits in JavaScript?


There is a code that performs calculations and outputs the result.

rez = Math.round(numb*pay*2.1/100);
$(".result p span").text(rez);

The task is to divide the output number by digits, i.e., instead of 1000000, output 1,000,000.

I try this option:

rez = Math.round(numb*pay*2.1/100);
var outrez = rez.replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ');
$(".result p span").text(outrez);

But there is no result at all. Tell me how to fix it. Thanks.

Author: Maksim Kukin, 2016-03-03

3 answers

Try this way:

(1000000).toLocaleString('ru')
 24
Author: DreamChild, 2016-03-03 09:09:06

Code with a regular expression also works.
The error is that Math.round - returns a number, and the number doesn't have a replace method, the string does. Therefore, the number should simply be reduced to a string.

var numb = 10572,
    pay = 11073;
rez = Math.round(numb*pay*2.1/100);
var outrez = (rez+'').replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ');

document.body.innerHTML = outrez;
 5
Author: Grundy, 2016-03-03 09:54:47

Here's another working option:

Number.prototype.toDivide = function() {
	var int = String(Math.trunc(this));
	if(int.length <= 3) return int;
	var space = 0;
	var number = '';

	for(var i = int.length - 1; i >= 0; i--) {
		if(space == 3) {
			number = ' ' + number;
			space = 0;
		}
		number = int.charAt(i) + number;
		space++;
	}

	return number;
}

var test0 = 1;
var test1 = 12;
var test2 = 123;
var test3 = 1234;
var test4 = 12345;
var test5 = 123456;
var test6 = 1234567;
var test7 = 12345678;
var test8 = 123456789;
var test9 = 1234567890;
console.log(test0.toDivide()); //1
console.log(test1.toDivide()); //12
console.log(test2.toDivide()); //123
console.log(test3.toDivide()); //1 234
console.log(test4.toDivide()); //12 345
console.log(test5.toDivide()); //123 456
console.log(test6.toDivide()); //1 234 567
console.log(test7.toDivide()); //12 345 678
console.log(test8.toDivide()); //123 456 789
console.log(test9.toDivide()); //1 234 567 890

On the plus side: it works for all numbers that will ever be created at once, and you can adjust them to your tastes)))

 1
Author: Руслан, 2020-02-18 18:31:56