type thousand separador quitar number money moneda miles formato bootstrap javascript jquery

javascript - thousand - jQuery: Número de formato de moneda



input type number thousand separator (8)

Tengo un número como este en mi html

<div class="number">950000</div>

y quiero que jQuery lo cambie a

<div class="number">Rp. 950.000</div>

¿Cómo puedo hacer eso en jQUery?


Aquí está el estilo fresco de expresiones regulares para agrupar dígitos:

thenumber.toString().replace(/(/d)(?=(/d{3})+(?!/d))/g, "$1.");


Divide entre 1000 y usa .toFixed(3) para fijar el número de lugares decimales.

var output = (input/1000).toFixed(3);

[EDITAR]

La solución anterior solo se aplica si el punto en la pregunta original es para un punto decimal. Sin embargo, el comentario del OP a continuación implica que está pensado como un separador de miles.

En este caso, no hay una solución de línea única (Javascript no la tiene incorporada), pero se puede lograr con una función bastante corta.

Puede encontrar un buen ejemplo aquí: http://www.mredkj.com/javascript/numberFormat.html#addcommas

Alternativamente, puede encontrar una función de formato de cadena más compleja que imita la printf() del lenguaje C aquí: http://www.diveintojavascript.com/projects/javascript-sprintf


Hay un complemento para eso, jquery-formatcurrency .

Puede configurar el separador decimal (predeterminado) y el símbolo de moneda ( $ predeterminado) para un formato personalizado o usar el Soporte internacional integrado. El formato para Bahasa Indonesia (Indonesia) - ID-ID codificado en Indonesia (Indonesia) es el más cercano a lo que ha proporcionado.


Por favor encuentre en el siguiente código lo que desarrollé para apoyar la internacionalización. Formatea el valor numérico dado al formato específico del idioma. En el ejemplo dado, he usado ''en'' mientras he probado ''es'' , ''fr'' y otros países donde varía el formato. No solo impide que el usuario teclee caracteres, sino que también da formato al valor de la pestaña. Se han creado componentes para el número , así como para el formato decimal . Además de esto, se han creado las funciones parseNumber (valor, configuración regional) y parseDecimal (valor, configuración regional) que analizarán los datos formateados para cualquier otro propósito comercial. Dicha función aceptará los datos formateados y devolverá el valor no formateado. He utilizado el complemento de validación JQuery en el siguiente código compartido.

HTML:

<tr> <td> <label class="control-label"> Number Field: </label> <div class="inner-addon right-addon"> <input type="text" id="numberField" name="numberField" class="form-control" autocomplete="off" maxlength="17" data-rule-required="true" data-msg-required="Cannot be blank." data-msg-maxlength="Exceeding the maximum limit of 13 digits. Example: 1234567890123" data-rule-numberExceedsMaxLimit="en" data-msg-numberExceedsMaxLimit="Exceeding the maximum limit of 13 digits. Example: 1234567890123" onkeydown="return isNumber(event, ''en'')" onkeyup="return updateField(this)" onblur="numberFormatter(this, ''en'', ''Invalid character(s) found. Please enter valid characters.'')"> </div> </td> </tr> <tr> <td> <label class="control-label"> Decimal Field: </label> <div class="inner-addon right-addon"> <input type="text" id="decimalField" name="decimalField" class="form-control" autocomplete="off" maxlength="20" data-rule-required="true" data-msg-required="Cannot be blank." data-msg-maxlength="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00" data-rule-decimalExceedsMaxLimit="en" data-msg-decimalExceedsMaxLimit="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00" onkeydown="return isDecimal(event, ''en'')" onkeyup="return updateField(this)" onblur="decimalFormatter(this, ''en'', ''Invalid character(s) found. Please enter valid characters.'')"> </div> </td> </tr>

JavaScript:

/* * @author: dinesh.lomte */ /* Holds the maximum limit of digits to be entered in number field. */ var numericMaxLimit = 13; /* Holds the maximum limit of digits to be entered in decimal field. */ var decimalMaxLimit = 16; /** * * @param {type} value * @param {type} locale * @returns {Boolean} */ parseDecimal = function(value, locale) { value = value.trim(); if (isNull(value)) { return 0.00; } if (isNull(locale)) { return value; } if (getNumberFormat(locale)[0] === ''.'') { value = value.replace(//./g, ''''); } else { value = value.replace( new RegExp(getNumberFormat(locale)[0], ''g''), ''''); } if (getNumberFormat(locale)[1] === '','') { value = value.replace( new RegExp(getNumberFormat(locale)[1], ''g''), ''.''); } return value; }; /** * * @param {type} element * @param {type} locale * @param {type} nanMessage * @returns {Boolean} */ decimalFormatter = function (element, locale, nanMessage) { showErrorMessage(element.id, false, null); if (isNull(element.id) || isNull(element.value) || isNull(locale)) { return true; } var value = element.value.trim(); value = value.replace(//s/g, ''''); value = parseDecimal(value, locale); var numberFormatObj = new Intl.NumberFormat(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 } ); if (numberFormatObj.format(value) === ''NaN'') { showErrorMessage(element.id, true, nanMessage); setFocus(element.id); return false; } element.value = numberFormatObj.format(value); return true; }; /** * * @param {type} element * @param {type} locale * @param {type} nanMessage * @returns {Boolean} */ numberFormatter = function (element, locale, nanMessage) { showErrorMessage(element.id, false, null); if (isNull(element.id) || isNull(element.value) || isNull(locale)) { return true; } var value = element.value.trim(); var format = getNumberFormat(locale); if (hasDecimal(value, format[1])) { showErrorMessage(element.id, true, nanMessage); setFocus(element.id); return false; } value = value.replace(//s/g, ''''); value = parseNumber(value, locale); var numberFormatObj = new Intl.NumberFormat(locale, { minimumFractionDigits: 0, maximumFractionDigits: 0 } ); if (numberFormatObj.format(value) === ''NaN'') { showErrorMessage(element.id, true, nanMessage); setFocus(element.id); return false; } element.value = numberFormatObj.format(value); return true; }; /** * * @param {type} id * @param {type} flag * @param {type} message * @returns {undefined} */ showErrorMessage = function(id, flag, message) { if (flag) { // only add if not added if ($(''#''+id).parent().next(''.app-error-message'').length === 0) { var errorTag = ''<div class=/'app-error-message/'>'' + message + ''</div>''; $(''#''+id).parent().after(errorTag); } } else { // remove it $(''#''+id).parent().next(".app-error-message").remove(); } }; /** * * @param {type} id * @returns */ setFocus = function(id) { id = id.trim(); if (isNull(id)) { return; } setTimeout(function() { document.getElementById(id).focus(); }, 10); }; /** * * @param {type} value * @param {type} locale * @returns {Array} */ parseNumber = function(value, locale) { value = value.trim(); if (isNull(value)) { return 0; } if (isNull(locale)) { return value; } if (getNumberFormat(locale)[0] === ''.'') { return value.replace(//./g, ''''); } return value.replace( new RegExp(getNumberFormat(locale)[0], ''g''), ''''); }; /** * * @param {type} locale * @returns {Array} */ getNumberFormat = function(locale) { var format = []; var numberFormatObj = new Intl.NumberFormat(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 } ); var value = numberFormatObj.format(''132617.07''); format[0] = value.charAt(3); format[1] = value.charAt(7); return format; }; /** * * @param {type} value * @param {type} fractionFormat * @returns {Boolean} */ hasDecimal = function(value, fractionFormat) { value = value.trim(); if (isNull(value) || isNull(fractionFormat)) { return false; } if (value.indexOf(fractionFormat) >= 1) { return true; } }; /** * * @param {type} event * @param {type} locale * @returns {Boolean} */ isNumber = function(event, locale) { var keyCode = event.which ? event.which : event.keyCode; // Validating if user has pressed shift character if (keyCode === 16) { return false; } if (isNumberKey(keyCode)) { return true; } var numberFormatter = [32, 110, 188, 190]; if (keyCode === 32 && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) { return true; } if (numberFormatter.indexOf(keyCode) >= 0 && getNumberFormat(locale)[0] === getFormat(keyCode)) { return true; } return false; }; /** * * @param {type} event * @param {type} locale * @returns {Boolean} */ isDecimal = function(event, locale) { var keyCode = event.which ? event.which : event.keyCode; // Validating if user has pressed shift character if (keyCode === 16) { return false; } if (isNumberKey(keyCode)) { return true; } var numberFormatter = [32, 110, 188, 190]; if (keyCode === 32 && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) { return true; } if (numberFormatter.indexOf(keyCode) >= 0 && (getNumberFormat(locale)[0] === getFormat(keyCode) || getNumberFormat(locale)[1] === getFormat(keyCode))) { return true; } return false; }; /** * * @param {type} keyCode * @returns {Boolean} */ isNumberKey = function(keyCode) { if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105)) { return true; } var keys = [8, 9, 13, 35, 36, 37, 39, 45, 46, 109, 144, 173, 189]; if (keys.indexOf(keyCode) !== -1) { return true; } return false; }; /** * * @param {type} keyCode * @returns {JSON@call;parse.numberFormatter.value|String} */ getFormat = function(keyCode) { var jsonString = ''{"numberFormatter" : [{"key":"32", "value":" ", "description":"space"}, {"key":"188", "value":",", "description":"comma"}, {"key":"190", "value":".", "description":"dot"}, {"key":"110", "value":".", "description":"dot"}]}''; var jsonObject = JSON.parse(jsonString); for (var key in jsonObject.numberFormatter) { if (jsonObject.numberFormatter.hasOwnProperty(key) && keyCode === parseInt(jsonObject.numberFormatter[key].key)) { return jsonObject.numberFormatter[key].value; } } return ''''; }; /** * * @type String */ var jsonString = ''{"shiftCharacterNumberMap" : [{"char":")", "number":"0"}, {"char":"!", "number":"1"}, {"char":"@", "number":"2"}, {"char":"#", "number":"3"}, {"char":"$", "number":"4"}, {"char":"%", "number":"5"}, {"char":"^", "number":"6"}, {"char":"&", "number":"7"}, {"char":"*", "number":"8"}, {"char":"(", "number":"9"}]}''; /** * * @param {type} value * @returns {JSON@call;parse.shiftCharacterNumberMap.number|String} */ getShiftCharSpecificNumber = function(value) { var jsonObject = JSON.parse(jsonString); for (var key in jsonObject.shiftCharacterNumberMap) { if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key) && value === jsonObject.shiftCharacterNumberMap[key].char) { return jsonObject.shiftCharacterNumberMap[key].number; } } return ''''; }; /** * * @param {type} value * @returns {Boolean} */ isShiftSpecificChar = function(value) { var jsonObject = JSON.parse(jsonString); for (var key in jsonObject.shiftCharacterNumberMap) { if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key) && value === jsonObject.shiftCharacterNumberMap[key].char) { return true; } } return false; }; /** * * @param {type} element * @returns {undefined} */ updateField = function(element) { var value = element.value; for (var index = 0; index < value.length; index++) { if (!isShiftSpecificChar(value.charAt(index))) { continue; } element.value = value.replace( value.charAt(index), getShiftCharSpecificNumber(value.charAt(index))); } }; /** * * @param {type} value * @param {type} element * @param {type} params */ jQuery.validator.addMethod(''numberExceedsMaxLimit'', function(value, element, params) { value = parseInt(parseNumber(value, params)); if (value.toString().length > numericMaxLimit) { showErrorMessage(element.id, false, null); setFocus(element.id); return false; } return true; }, ''Exceeding the maximum limit of 13 digits. Example: 1234567890123.''); /** * * @param {type} value * @param {type} element * @param {type} params */ jQuery.validator.addMethod(''decimalExceedsMaxLimit'', function(value, element, params) { value = parseFloat(parseDecimal(value, params)).toFixed(2); if (value.toString().substring( 0, value.toString().lastIndexOf(''.'')).length > numericMaxLimit || value.toString().length > decimalMaxLimit) { showErrorMessage(element.id, false, null); setFocus(element.id); return false; } return true; }, ''Exceeding the maximum limit of 16 digits. Example: 1234567890123.00.''); /** * @param {type} id * @param {type} locale * @returns {boolean} */ isNumberExceedMaxLimit = function(id, locale) { var value = parseInt(parseNumber( document.getElementById(id).value, locale)); if (value.toString().length > numericMaxLimit) { setFocus(id); return true; } return false; }; /** * @param {type} id * @param {type} locale * @returns {boolean} */ isDecimalExceedsMaxLimit = function(id, locale) { var value = parseFloat(parseDecimal( document.getElementById(id).value, locale)).toFixed(2); if (value.toString().substring( 0, value.toString().lastIndexOf(''.'')).length > numericMaxLimit || value.toString().length > decimalMaxLimit) { setFocus(id); return true; } return false; };


Puede utilizar esta forma para formatear su moneda que necesite.

var xx = new Intl.NumberFormat(‘en-US’, { style: ‘currency’, currency: ‘USD’, minimumFractionDigits: 2, maximumFractionDigits: 2 }); xx.format(123456.789); // ‘$123,456.79’

Para más información puedes acceder a este enlace.

https://www.justinmccandless.com/post/formatting-currency-in-javascript/


var input=950000; var output=parseInt(input).toLocaleString(); alert(output);


function converter() { var number = $(.number).text(); var number = ''Rp. ''+number; s(.number).val(number); }


$(document).ready(function() { var num = $(''div.number'').text() num = addPeriod(num); $(''div.number'').text(''Rp. ''+num) }); function addPeriod(nStr) { nStr += ''''; x = nStr.split(''.''); x1 = x[0]; x2 = x.length > 1 ? ''.'' + x[1] : ''''; var rgx = /(/d+)(/d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, ''$1'' + ''.'' + ''$2''); } return x1 + x2; }