31

I have number like this in my html

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

and I want jQuery change it to

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

How can I do that in jQUery?

4
  • 2
    Do you have the option of formatting this server-side? Commented Apr 27, 2011 at 16:17
  • @richard in some case i want to do this in jQuery/JavaScript :) Commented Apr 27, 2011 at 16:27
  • 1
    developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented Nov 28, 2015 at 9:16
  • @zloctb Thank you for posting your answer here years later. This helped me SO MUCH!! The only solution that really makes sense, And it's sooo easy now. Commented Apr 15, 2019 at 11:01

9 Answers 9

36

Divide by 1000, and use .toFixed(3) to fix the number of decimal places.

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

[EDIT]

The above solution only applies if the dot in the original question is for a decimal point. However the OP's comment below implies that it is intended as a thousands separator.

In this case, there isn't a single line solution (Javascript doesn't have it built in), but it can be achieved with a fairly short function.

A good example can be found here: http://www.mredkj.com/javascript/numberFormat.html#addcommas

Alternatively, a more complex string formatting function which mimics the printf() function from the C language can be found here: http://www.diveintojavascript.com/projects/javascript-sprintf

Sign up to request clarification or add additional context in comments.

4 Comments

what will happen if later i have number like this 5550000000 is this will working correctly?
I guess I should have asked whether the dot is a decimal point or a thousands separator. This answer only applies if it's a decimal point.
@GusDe - I've edited my answer to give a solution for both cases.
Thank you Spudley, this is really help :)
23

Here is the cool regex style for digit grouping:

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

3 Comments

I used this to get my currency formatted with commas instead of periods.
@Mowd you can replace the dot in "$1." with ,
Since this page comes up when I search this question (and it'll happen again I'm sure) here's how I get both decimal and commas in my number: thenumber.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
8

There is a plugin for that, jquery-formatcurrency.

You can set the decimal separator (default .) and currency symbol (default $) for custom formatting or use the built in International Support. The format for Bahasa Indonesia (Indonesia) - Indonesian (Indonesia) coded id-ID looks closest to what you have provided.

3 Comments

i avoid using plugin, since i only need simple method and want to know the logic how to that in jQuery :)
@GusDe CooL - if you don't want to use a plugin then a combination of Spudley's answer to divide and use toFixed and Praneeth's answer to append 'Rp. ' should set you up.
this plugin have bug. Returns wrong value when value is greater than 15 in length
8

You can use this way to format your currency needing.

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

For more info you can access this link.

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

1 Comment

This is very useful when you need to use different currencies or your locale is not the same as default
7

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

Comments

4
$(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; } 

Comments

1

Please find in the below code what I developed to support internationalization. It formats the given numeric value to language specific format. In the given example I have used ‘en’ while have tested for ‘es’, ‘fr’ and other countries where in the format varies. It not only stops user from keying characters but formats the value on tab out. Have created components for Number as well as for Decimal format. Apart from this have created parseNumber(value, locale) and parseDecimal(value, locale) functions which will parse the formatted data for any other business purposes. The said function will accept the formatted data and will return the non-formatted value. I have used JQuery validator plugin in the below shared code.

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; }; 

Comments

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

1 Comment

are you sure using .val() since this is not input tag?
0

you can also do it using Inputmask Library ...

for demo see here

$(document).ready(function(){ $("#amount").inputmask('decimal', { 'alias': 'numeric', 'groupSeparator': ',', 'digits': 2, 'digitsOptional': false, // 'prefix': 'Rs ', 'placeholder': '0', /* 'autoGroup': true, 'radixPoint': ".", 'allowMinus': false,*/ }); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.