Skip to content

Instantly share code, notes, and snippets.

@saltun
Created December 19, 2017 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saltun/1582fa1b16c96e8ae4768a4e1949473f to your computer and use it in GitHub Desktop.
Save saltun/1582fa1b16c96e8ae4768a4e1949473f to your computer and use it in GitHub Desktop.
JavaScript cut number
// Turkish
function cutNumber(value) {
var newValue = value;
if (value >= 1000) {
var suffixes = ["", "Bin", "Milyon", "Milyar"," Trilyon"];
var suffixNum = Math.floor( (""+value).length/3 );
var shortValue = '';
for (var precision = 2; precision >= 1; precision--) {
shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));
var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
if (dotLessShortValue.length <= 2) { break; }
}
if (shortValue % 1 != 0) shortNum = shortValue.toFixed(1);
newValue = shortValue+suffixes[suffixNum];
}
return newValue;
}
cutNumber(1124373258947) // 1.1 Trilyon
// English
function cutNumber(value) {
var newValue = value;
if (value >= 1000) {
var suffixes = ["", "Thousand", "Million", "Billion"," Trillion"];
var suffixNum = Math.floor( (""+value).length/3 );
var shortValue = '';
for (var precision = 2; precision >= 1; precision--) {
shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));
var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
if (dotLessShortValue.length <= 2) { break; }
}
if (shortValue % 1 != 0) shortNum = shortValue.toFixed(1);
newValue = shortValue+suffixes[suffixNum];
}
return newValue;
}
cutNumber(1124373258947) // 1.1 Trilyon
// English cut
function cutNumber(value) {
var newValue = value;
if (value >= 1000) {
var suffixes = ["", "k", "m", "b","t"];
var suffixNum = Math.floor( (""+value).length/3 );
var shortValue = '';
for (var precision = 2; precision >= 1; precision--) {
shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));
var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
if (dotLessShortValue.length <= 2) { break; }
}
if (shortValue % 1 != 0) shortNum = shortValue.toFixed(1);
newValue = shortValue+suffixes[suffixNum];
}
return newValue;
}
cutNumber(1000) // 1k
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment