"Formato de moneda en JavaScript"
Bootstrap 3.0.0 Snippet by nadiiavaaL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<div class="container">
<div class="form-group">
<h1>Formato de moneda en JavaScript</h1>
</div>
<div class="col-md-8 form-group">
<div class="input-group">
<span class="input-group-addon blue"><span class="glyphicon glyphicon-pencil"></span></span>
<input id="monedaInput" placeholder="Escribe número" type="text" class="form-control">
</div>
</div>
<div class="col-md-8">
<button id="change" onclick="monedaChange()" class="btn btn-primary"> Dar Formato </button>
</div>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
2
3
4
5
.input-group-addon.blue {
color: rgb(255, 255, 255);
background-color: rgb(50, 118, 177);
border-color: rgb(40, 94, 142);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function monedaChange (cif = 3, dec = 2) {
// tomamos el valor que tiene el input
let inputNum = document.getElementById('monedaInput').value
// Lo convertimos en texto
inputNum = inputNum.toString()
// separamos en un array los valores antes y después del punto
inputNum = inputNum.split('.')
// evaluamos si existen decimales
if (!inputNum[1]) {
inputNum[1] = '00'
}
let separados
// se calcula la longitud de la cadena
if (inputNum[0].length > cif) {
let uno = inputNum[0].length % cif
if (uno === 0) {
separados = []
} else {
separados = [inputNum[0].substring(0, uno)]
}
let posiciones = parseInt(inputNum[0].length / cif)
for (let i = 0; i < posiciones; i++) {
let pos = ((i * cif) + uno)
console.log(uno, pos)
separados.push(inputNum[0].substring(pos, (pos + 3)))
}
} else {
separados = [inputNum[0]]
}
document.getElementById('monedaInput').value = '$' + separados.join(',') + '.' + inputNum[1]
};
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Related: See More


Questions / Comments: