Cara hitung berapa jumlah angka di depan/belakang koma/desimal menggunakan javascript adalah sebagai berikut:
- Alternatif 1
function retr_before_dec(num) {
return (num.split('.')[0] || []).length;
}
function retr_after_dec(num) {
return (num.split('.')[1] || []).length;
}
return (num.split('.')[0] || []).length;
}
function retr_after_dec(num) {
return (num.split('.')[1] || []).length;
}
- Alternatif 2
function decimalPlaces(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0)
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0)
);
}
}
- Alternatif 3
function comma(num) {
var s = num.split('.');
var beforeDecimal = s[0]; // This is the number BEFORE the decimal.
var afterDecimal = '0001'; // Default value for digits after decimal
if (s.length > 1) // Check that there indeed is a decimal separator.
afterDecimal = s[1]; // This is the number AFTER the decimal.
if (beforeDecimal.length > 2) {
// Too many numbers before decimal.
// Get the first 2 digits and discard the rest.
beforeDecimal = beforeDecimal.substring(0, 2);
}
if (afterDecimal.length > 4) {
// Too many numbers after decimal.
// Get the first 4 digits and discard the rest.
afterDecimal = afterDecimal.substring(0, 4);
}
// Return the new number with at most 14 digits before the decimal
// and at most 4 after.
return beforeDecimal + "." + afterDecimal;
}
- to be continue....
Sekian, terimakasih atas kunjungannya.
Salam,
PHP Aku : Membangun web terorganisasi dan mudah dimengerti, contoh tutorial dengan menggunakan HTML, CSS, JavaScript, SQL, PHP, dan XML.
EmoticonEmoticon