mammam mammam - 2 months ago 7
Javascript Question

how to get western number pattern (seperated with commas)

my value is coming in input like

3440.00
, But need to show like
3,440.00


more example:
10,05,000.00
should be
1,005,000.00


I got my data from spring mvc with thymeleaf

<input type="text" class="form-control inputData" id="abcd" th:value="${selectedDetails.abcd}" readonly="readonly"/>


js is:

$(document).ready(function() {

var a=$("#abcd").val();
console.log(a);

function *format(a)* {
console.log(acquisitionCost);
return a.toLocaleString("en", { useGrouping: true,});
}


I hope my problem is in Javascript. how I will call method format?

help please.

Answer

Please check below snippet.

function format1(n) {
  n = parseFloat(n);
  return n.toFixed(2).replace(/./g, function(c, i, a) {
    return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
  });
}
$(document).ready(function(){
  var a = $("#abcd").val();
  console.log(format1(a));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control inputData"  id="abcd"  value="12345.67" readonly="readonly"/>

Update

//Textfield value
var a = $("#abcd").val();
//Number format the value
var formatted_a = format1(a);