-
Star
(105)
You must be signed in to star a gist -
Fork
(53)
You must be signed in to fork a gist
/*************************************************************/ | |
// NumeroALetras | |
// The MIT License (MIT) | |
// | |
// Copyright (c) 2015 Luis Alfredo Chee | |
// | |
// Permission is hereby granted, free of charge, to any person obtaining a copy | |
// of this software and associated documentation files (the "Software"), to deal | |
// in the Software without restriction, including without limitation the rights | |
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
// copies of the Software, and to permit persons to whom the Software is | |
// furnished to do so, subject to the following conditions: | |
// | |
// The above copyright notice and this permission notice shall be included in all | |
// copies or substantial portions of the Software. | |
// | |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
// SOFTWARE. | |
// | |
// @author Rodolfo Carmona | |
// @contributor Jean (jpbadoino@gmail.com) | |
/*************************************************************/ | |
function Unidades(num){ | |
switch(num) | |
{ | |
case 1: return “UN”; | |
case 2: return “DOS”; | |
case 3: return “TRES”; | |
case 4: return “CUATRO”; | |
case 5: return “CINCO”; | |
case 6: return “SEIS”; | |
case 7: return “SIETE”; | |
case 8: return “OCHO”; | |
case 9: return “NUEVE”; | |
} | |
return “”; | |
}//Unidades() | |
function Decenas(num){ | |
decena = Math.floor(num/10); | |
unidad = num – (decena * 10); | |
switch(decena) | |
{ | |
case 1: | |
switch(unidad) | |
{ | |
case 0: return “DIEZ”; | |
case 1: return “ONCE”; | |
case 2: return “DOCE”; | |
case 3: return “TRECE”; | |
case 4: return “CATORCE”; | |
case 5: return “QUINCE”; | |
default: return “DIECI” + Unidades(unidad); | |
} | |
case 2: | |
switch(unidad) | |
{ | |
case 0: return “VEINTE”; | |
default: return “VEINTI” + Unidades(unidad); | |
} | |
case 3: return DecenasY(“TREINTA”, unidad); | |
case 4: return DecenasY(“CUARENTA”, unidad); | |
case 5: return DecenasY(“CINCUENTA”, unidad); | |
case 6: return DecenasY(“SESENTA”, unidad); | |
case 7: return DecenasY(“SETENTA”, unidad); | |
case 8: return DecenasY(“OCHENTA”, unidad); | |
case 9: return DecenasY(“NOVENTA”, unidad); | |
case 0: return Unidades(unidad); | |
} | |
}//Unidades() | |
function DecenasY(strSin, numUnidades) { | |
if (numUnidades > 0) | |
return strSin + ” Y ” + Unidades(numUnidades) | |
return strSin; | |
}//DecenasY() | |
function Centenas(num) { | |
centenas = Math.floor(num / 100); | |
decenas = num – (centenas * 100); | |
switch(centenas) | |
{ | |
case 1: | |
if (decenas > 0) | |
return “CIENTO ” + Decenas(decenas); | |
return “CIEN”; | |
case 2: return “DOSCIENTOS ” + Decenas(decenas); | |
case 3: return “TRESCIENTOS ” + Decenas(decenas); | |
case 4: return “CUATROCIENTOS ” + Decenas(decenas); | |
case 5: return “QUINIENTOS ” + Decenas(decenas); | |
case 6: return “SEISCIENTOS ” + Decenas(decenas); | |
case 7: return “SETECIENTOS ” + Decenas(decenas); | |
case 8: return “OCHOCIENTOS ” + Decenas(decenas); | |
case 9: return “NOVECIENTOS ” + Decenas(decenas); | |
} | |
return Decenas(decenas); | |
}//Centenas() | |
function Seccion(num, divisor, strSingular, strPlural) { | |
cientos = Math.floor(num / divisor) | |
resto = num – (cientos * divisor) | |
letras = “”; | |
if (cientos > 0) | |
if (cientos > 1) | |
letras = Centenas(cientos) + ” ” + strPlural; | |
else | |
letras = strSingular; | |
if (resto > 0) | |
letras += “”; | |
return letras; | |
}//Seccion() | |
function Miles(num) { | |
divisor = 1000; | |
cientos = Math.floor(num / divisor) | |
resto = num – (cientos * divisor) | |
strMiles = Seccion(num, divisor, “UN MIL”, “MIL”); | |
strCentenas = Centenas(resto); | |
if(strMiles == “”) | |
return strCentenas; | |
return strMiles + ” ” + strCentenas; | |
}//Miles() | |
function Millones(num) { | |
divisor = 1000000; | |
cientos = Math.floor(num / divisor) | |
resto = num – (cientos * divisor) | |
strMillones = Seccion(num, divisor, “UN MILLON DE”, “MILLONES DE”); | |
strMiles = Miles(resto); | |
if(strMillones == “”) | |
return strMiles; | |
return strMillones + ” ” + strMiles; | |
}//Millones() | |
function NumeroALetras(num) { | |
var data = { | |
numero: num, | |
enteros: Math.floor(num), | |
centavos: (((Math.round(num * 100)) – (Math.floor(num) * 100))), | |
letrasCentavos: “”, | |
letrasMonedaPlural: 'Córdobas',//“PESOS”, 'Dólares', 'Bolívares', 'etcs' | |
letrasMonedaSingular: 'Córdoba', //“PESO”, 'Dólar', 'Bolivar', 'etc' | |
letrasMonedaCentavoPlural: “CENTAVOS”, | |
letrasMonedaCentavoSingular: “CENTAVO” | |
}; | |
if (data.centavos > 0) { | |
data.letrasCentavos = “CON ” + (function (){ | |
if (data.centavos == 1) | |
return Millones(data.centavos) + ” ” + data.letrasMonedaCentavoSingular; | |
else | |
return Millones(data.centavos) + ” ” + data.letrasMonedaCentavoPlural; | |
})(); | |
}; | |
if(data.enteros == 0) | |
return “CERO ” + data.letrasMonedaPlural + ” ” + data.letrasCentavos; | |
if (data.enteros == 1) | |
return Millones(data.enteros) + ” ” + data.letrasMonedaSingular + ” ” + data.letrasCentavos; | |
else | |
return Millones(data.enteros) + ” ” + data.letrasMonedaPlural + ” ” + data.letrasCentavos; | |
}//NumeroALetras() |
// Me ayudo! gracias por la aporte!
// para bolivianos (FACTURAS) pequeña modificación
// numeroALetras(543.15) // QUINIENTOS CUARENTA Y TRES 15/100 BOLIVIANOS`
return function NumeroALetras(num, currency) { currency = currency || {}; let data = { numero: num, enteros: Math.floor(num), centavos: (((Math.round(num * 100)) - (Math.floor(num) * 100))), letrasCentavos: '', letrasMonedaPlural: currency.plural || 'BOLIVIANOS' // Solo usa el plural };
`
data.letrasCentavos = ' ' + (function () {
if (data.centavos > 9)
return data.centavos + '/100 ' + data.letrasMonedaPlural;
else
return '0' + data.centavos + '/100 ' + data.letrasMonedaPlural;
})();
if(data.enteros == 0)
return 'CERO' + data.letrasCentavos;
if (data.enteros == 1)
return Millones(data.enteros) + data.letrasCentavos;
else
return Millones(data.enteros) + data.letrasCentavos;
};
})();
`
Corregido sería así (los globales y los tokens de string):
var numeroALetras = (function() { // Código basado en https://gist.github.com/alfchee/e563340276f89b22042a function Unidades(num){ switch(num) { case 1: return 'UN'; case 2: return 'DOS'; case 3: return 'TRES'; case 4: return 'CUATRO'; case 5: return 'CINCO'; case 6: return 'SEIS'; case 7: return 'SIETE'; case 8: return 'OCHO'; case 9: return 'NUEVE'; } return ''; }//Unidades() function Decenas(num){ let decena = Math.floor(num/10); let unidad = num - (decena * 10); switch(decena) { case 1: switch(unidad) { case 0: return 'DIEZ'; case 1: return 'ONCE'; case 2: return 'DOCE'; case 3: return 'TRECE'; case 4: return 'CATORCE'; case 5: return 'QUINCE'; default: return 'DIECI' + Unidades(unidad); } case 2: switch(unidad) { case 0: return 'VEINTE'; default: return 'VEINTI' + Unidades(unidad); } case 3: return DecenasY('TREINTA', unidad); case 4: return DecenasY('CUARENTA', unidad); case 5: return DecenasY('CINCUENTA', unidad); case 6: return DecenasY('SESENTA', unidad); case 7: return DecenasY('SETENTA', unidad); case 8: return DecenasY('OCHENTA', unidad); case 9: return DecenasY('NOVENTA', unidad); case 0: return Unidades(unidad); } }//Unidades() function DecenasY(strSin, numUnidades) { if (numUnidades > 0) return strSin + ' Y ' + Unidades(numUnidades) return strSin; }//DecenasY() function Centenas(num) { let centenas = Math.floor(num / 100); let decenas = num - (centenas * 100); switch(centenas) { case 1: if (decenas > 0) return 'CIENTO ' + Decenas(decenas); return 'CIEN'; case 2: return 'DOSCIENTOS ' + Decenas(decenas); case 3: return 'TRESCIENTOS ' + Decenas(decenas); case 4: return 'CUATROCIENTOS ' + Decenas(decenas); case 5: return 'QUINIENTOS ' + Decenas(decenas); case 6: return 'SEISCIENTOS ' + Decenas(decenas); case 7: return 'SETECIENTOS ' + Decenas(decenas); case 8: return 'OCHOCIENTOS ' + Decenas(decenas); case 9: return 'NOVECIENTOS ' + Decenas(decenas); } return Decenas(decenas); }//Centenas() function Seccion(num, divisor, strSingular, strPlural) { let cientos = Math.floor(num / divisor) let resto = num - (cientos * divisor) let letras = ''; if (cientos > 0) if (cientos > 1) letras = Centenas(cientos) + ' ' + strPlural; else letras = strSingular; if (resto > 0) letras += ''; return letras; }//Seccion() function Miles(num) { let divisor = 1000; let cientos = Math.floor(num / divisor) let resto = num - (cientos * divisor) let strMiles = Seccion(num, divisor, 'UN MIL', 'MIL'); let strCentenas = Centenas(resto); if(strMiles == '') return strCentenas; return strMiles + ' ' + strCentenas; }//Miles() function Millones(num) { let divisor = 1000000; let cientos = Math.floor(num / divisor) let resto = num - (cientos * divisor) let strMillones = Seccion(num, divisor, 'UN MILLON DE', 'MILLONES DE'); let strMiles = Miles(resto); if(strMillones == '') return strMiles; return strMillones + ' ' + strMiles; }//Millones() return function NumeroALetras(num, currency) { currency = currency || {}; let data = { numero: num, enteros: Math.floor(num), centavos: (((Math.round(num * 100)) - (Math.floor(num) * 100))), letrasCentavos: '', letrasMonedaPlural: currency.plural || 'PESOS CHILENOS',//'PESOS', 'Dólares', 'Bolívares', 'etcs' letrasMonedaSingular: currency.singular || 'PESO CHILENO', //'PESO', 'Dólar', 'Bolivar', 'etc' letrasMonedaCentavoPlural: currency.centPlural || 'CHIQUI PESOS CHILENOS', letrasMonedaCentavoSingular: currency.centSingular || 'CHIQUI PESO CHILENO' }; if (data.centavos > 0) { data.letrasCentavos = 'CON ' + (function () { if (data.centavos == 1) return Millones(data.centavos) + ' ' + data.letrasMonedaCentavoSingular; else return Millones(data.centavos) + ' ' + data.letrasMonedaCentavoPlural; })(); }; if(data.enteros == 0) return 'CERO ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos; if (data.enteros == 1) return Millones(data.enteros) + ' ' + data.letrasMonedaSingular + ' ' + data.letrasCentavos; else return Millones(data.enteros) + ' ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos; }; })(); // Modo de uso: 500,34 USD numeroALetras(500.34, { plural: 'dólares estadounidenses', singular: 'dólar estadounidense', centPlural: 'centavos', centSingular: 'centavo' });
Genial amigo, muchas gracias, me ahorraste varias horas de trabajo.
Adecuado para Angular 5 -- Service - Saludos desde Peru- Lima
import { Injectable } from '@angular/core';
@Injectable()
export class Utils {Unidades(num){ switch(num) { case 1: return 'UN'; case 2: return 'DOS'; case 3: return 'TRES'; case 4: return 'CUATRO'; case 5: return 'CINCO'; case 6: return 'SEIS'; case 7: return 'SIETE'; case 8: return 'OCHO'; case 9: return 'NUEVE'; } return ''; }//Unidades() Decenas(num){ let decena = Math.floor(num/10); let unidad = num - (decena * 10); switch(decena) { case 1: switch(unidad) { case 0: return 'DIEZ'; case 1: return 'ONCE'; case 2: return 'DOCE'; case 3: return 'TRECE'; case 4: return 'CATORCE'; case 5: return 'QUINCE'; default: return 'DIECI' + this.Unidades(unidad); } case 2: switch(unidad) { case 0: return 'VEINTE'; default: return 'VEINTI' + this.Unidades(unidad); } case 3: return this.DecenasY('TREINTA', unidad); case 4: return this.DecenasY('CUARENTA', unidad); case 5: return this.DecenasY('CINCUENTA', unidad); case 6: return this.DecenasY('SESENTA', unidad); case 7: return this.DecenasY('SETENTA', unidad); case 8: return this.DecenasY('OCHENTA', unidad); case 9: return this.DecenasY('NOVENTA', unidad); case 0: return this.Unidades(unidad); } }//Unidades() DecenasY(strSin, numUnidades) { if (numUnidades > 0) return strSin + ' Y ' + this.Unidades(numUnidades) return strSin; }//DecenasY() Centenas(num) { let centenas = Math.floor(num / 100); let decenas = num - (centenas * 100); switch(centenas) { case 1: if (decenas > 0) return 'CIENTO ' + this.Decenas(decenas); return 'CIEN'; case 2: return 'DOSCIENTOS ' + this.Decenas(decenas); case 3: return 'TRESCIENTOS ' + this.Decenas(decenas); case 4: return 'CUATROCIENTOS ' + this.Decenas(decenas); case 5: return 'QUINIENTOS ' + this.Decenas(decenas); case 6: return 'SEISCIENTOS ' + this.Decenas(decenas); case 7: return 'SETECIENTOS ' + this.Decenas(decenas); case 8: return 'OCHOCIENTOS ' + this.Decenas(decenas); case 9: return 'NOVECIENTOS ' + this.Decenas(decenas); } return this.Decenas(decenas); }//Centenas() Seccion(num, divisor, strSingular, strPlural) { let cientos = Math.floor(num / divisor) let resto = num - (cientos * divisor) let letras = ''; if (cientos > 0) if (cientos > 1) letras = this.Centenas(cientos) + ' ' + strPlural; else letras = strSingular; if (resto > 0) letras += ''; return letras; }//Seccion() Miles(num) { let divisor = 1000; let cientos = Math.floor(num / divisor) let resto = num - (cientos * divisor) let strMiles = this.Seccion(num, divisor, 'UN MIL', 'MIL'); let strCentenas = this.Centenas(resto); if(strMiles == '') return strCentenas; return strMiles + ' ' + strCentenas; }//Miles() Millones(num) { let divisor = 1000000; let cientos = Math.floor(num / divisor) let resto = num - (cientos * divisor) let strMillones = this.Seccion(num, divisor, 'UN MILLON DE', 'MILLONES DE'); let strMiles = this.Miles(resto); if(strMillones == '') return strMiles; return strMillones + ' ' + strMiles; }//Millones() numeroALetras(num, currency) { currency = currency || {}; let data = { numero: num, enteros: Math.floor(num), centavos: (((Math.round(num * 100)) - (Math.floor(num) * 100))), letrasCentavos: '', letrasMonedaPlural: currency.plural || 'PESOS CHILENOS',//'PESOS', 'Dólares', 'Bolívares', 'etcs' letrasMonedaSingular: currency.singular || 'PESO CHILENO', //'PESO', 'Dólar', 'Bolivar', 'etc' letrasMonedaCentavoPlural: currency.centPlural || 'CHIQUI PESOS CHILENOS', letrasMonedaCentavoSingular: currency.centSingular || 'CHIQUI PESO CHILENO' }; if (data.centavos > 0) { let centavos = '' if (data.centavos == 1) centavos = this.Millones(data.centavos) + ' ' + data.letrasMonedaCentavoSingular; else centavos = this.Millones(data.centavos) + ' ' + data.letrasMonedaCentavoPlural; data.letrasCentavos = 'CON ' + centavos }; if(data.enteros == 0) return 'CERO ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos; if (data.enteros == 1) return this.Millones(data.enteros) + ' ' + data.letrasMonedaSingular + ' ' + data.letrasCentavos; else return this.Millones(data.enteros) + ' ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos; };
}
ORDENA TU CODIGO PERROOOOOOOOOOOOOOOOOOOOO
import { Injectable } from '@angular/core';
@Injectable()
export class ClaseMonedaLiteral {
Unidades(num) {
switch (num) {
case 1: return 'UN';
case 2: return 'DOS';
case 3: return 'TRES';
case 4: return 'CUATRO';
case 5: return 'CINCO';
case 6: return 'SEIS';
case 7: return 'SIETE';
case 8: return 'OCHO';
case 9: return 'NUEVE';
}
return '';
}
// Unidades()
Decenas(num) {
const decena = Math.floor(num / 10);
const unidad = num - (decena * 10);
switch (decena) {
case 1:
switch (unidad) {
case 0: return 'DIEZ';
case 1: return 'ONCE';
case 2: return 'DOCE';
case 3: return 'TRECE';
case 4: return 'CATORCE';
case 5: return 'QUINCE';
default: return 'DIECI' + this.Unidades(unidad);
}
case 2:
switch (unidad) {
case 0: return 'VEINTE';
default: return 'VEINTI' + this.Unidades(unidad);
}
case 3: return this.DecenasY('TREINTA', unidad);
case 4: return this.DecenasY('CUARENTA', unidad);
case 5: return this.DecenasY('CINCUENTA', unidad);
case 6: return this.DecenasY('SESENTA', unidad);
case 7: return this.DecenasY('SETENTA', unidad);
case 8: return this.DecenasY('OCHENTA', unidad);
case 9: return this.DecenasY('NOVENTA', unidad);
case 0: return this.Unidades(unidad);
}
}// Unidades()
DecenasY(strSin, numUnidades) {
if (numUnidades > 0) {
return strSin + ' Y ' + this.Unidades(numUnidades);
}
return strSin;
}// DecenasY()
Centenas(num) {
const centenas = Math.floor(num / 100);
const decenas = num - (centenas * 100);
switch (centenas) {
case 1:
if (decenas > 0) {
return 'CIENTO ' + this.Decenas(decenas);
}
return 'CIEN';
case 2: return 'DOSCIENTOS ' + this.Decenas(decenas);
case 3: return 'TRESCIENTOS ' + this.Decenas(decenas);
case 4: return 'CUATROCIENTOS ' + this.Decenas(decenas);
case 5: return 'QUINIENTOS ' + this.Decenas(decenas);
case 6: return 'SEISCIENTOS ' + this.Decenas(decenas);
case 7: return 'SETECIENTOS ' + this.Decenas(decenas);
case 8: return 'OCHOCIENTOS ' + this.Decenas(decenas);
case 9: return 'NOVECIENTOS ' + this.Decenas(decenas);
}
return this.Decenas(decenas);
}// Centenas()
Seccion(num, divisor, strSingular, strPlural) {
const cientos = Math.floor(num / divisor);
const resto = num - (cientos * divisor);
let letras = '';
if (cientos > 0) {
if (cientos > 1) {
letras = this.Centenas(cientos) + ' ' + strPlural;
} else {
letras = strSingular;
}
}
if (resto > 0) {
letras += '';
}
return letras;
}// Seccion()
Miles(num) {
const divisor = 1000;
const cientos = Math.floor(num / divisor);
const resto = num - (cientos * divisor);
const strMiles = this.Seccion(num, divisor, 'UN MIL', 'MIL');
const strCentenas = this.Centenas(resto);
if (strMiles === '') {
return strCentenas;
}
return strMiles + ' ' + strCentenas;
}// Miles()
Millones(num) {
const divisor = 1000000;
const cientos = Math.floor(num / divisor);
const resto = num - (cientos * divisor);
const strMillones = this.Seccion(num, divisor, 'UN MILLON DE', 'MILLONES DE');
const strMiles = this.Miles(resto);
if (strMillones === '') {
return strMiles;
}
return strMillones + ' ' + strMiles;
}// Millones()
numeroALetras(num, currency) {
currency = currency || {};
const data = {
numero: num,
enteros: Math.floor(num),
centavos: (((Math.round(num * 100)) - (Math.floor(num) * 100))),
letrasCentavos: '',
letrasMonedaPlural: currency.plural || 'PESOS CHILENOS', // 'PESOS', 'Dólares', 'Bolívares', 'etcs'
letrasMonedaSingular: currency.singular || 'PESO CHILENO', // 'PESO', 'Dólar', 'Bolivar', 'etc'
letrasMonedaCentavoPlural: currency.centPlural || 'CHIQUI PESOS CHILENOS',
letrasMonedaCentavoSingular: currency.centSingular || 'CHIQUI PESO CHILENO'
};
if (data.centavos > 0) {
let centavos = '';
if (data.centavos === 1) {
centavos = this.Millones(data.centavos) + ' ' + data.letrasMonedaCentavoSingular;
} else {
centavos = this.Millones(data.centavos) + ' ' + data.letrasMonedaCentavoPlural;
}
data.letrasCentavos = 'CON ' + centavos;
}
if (data.enteros === 0) {
return 'CERO ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos;
}
if (data.enteros === 1) {
return this.Millones(data.enteros) + ' ' + data.letrasMonedaSingular + ' ' + data.letrasCentavos;
} else {
return this.Millones(data.enteros) + ' ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos;
}
}
}
Hice algunas correcciones a tu código y agregué un archivo con tests.
https://gist.github.com/blkdr/a3aca384dd2fa002f6926b49752322cf
Si alquien lo necesita en billones:
`function MilMillones(num) {
var divisor = 1000000000;
var cientos = Math.floor(num / divisor);
var resto = num - (cientos * divisor);
var strMilMillones = Seccion(num, divisor, 'UN MIL', 'MIL');
if (cientos > 0 && resto === 0)
strMilMillones += ' MILLONES';
var strMillones = Millones(resto);
if (strMilMillones === '')
return strMillones;
return strMilMillones + ' ' + strMillones;
} // MilMillones()
function Billones(num) {
var divisor = 1000000000000;
var cientos = Math.floor(num / divisor);
var resto = num - (cientos * divisor);
var strBillones = Seccion(num, divisor, 'UN BILLON', 'BILLONES');
var strMilMillones = MilMillones(resto);
if (strBillones === '')
return strMilMillones;
return strBillones + ' ' + strMilMillones;
} // Billones()
return function NumeroALetras(num, currency) {
currency = currency || {};
var data = {
numero: num,
enteros: Math.floor(num),
centavos: (((Math.round(num * 100)) - (Math.floor(num) * 100))),
letrasCentavos: '',
letrasMonedaPlural: currency.plural || 'BOLIVIANOS', //'PESOS', 'Dólares', 'Bolívares', 'etcs'
letrasMonedaSingular: currency.singular || 'BOLIVIANO', //'PESO', 'Dólar', 'Bolivar', 'etc'
letrasMonedaCentavoPlural: currency.centPlural || 'CENTAVOS DE BOLIVIANO',
letrasMonedaCentavoSingular: currency.centSingular || 'CENTAVO DE BOLIVIANO'
};
if (data.centavos > 0) {
data.letrasCentavos = (function () {
return data.centavos + '/100 ' + data.letrasMonedaPlural;
})();
} else {
data.letrasCentavos = (function () {
return '00/100 ' + data.letrasMonedaPlural;
})();
}
if (data.enteros === 0)
return 'CERO ' + data.letrasCentavos;
if (data.enteros === 1)
return Billones(data.enteros) + ' ' + data.letrasCentavos;
else
return Billones(data.enteros) + ' ' + data.letrasCentavos;
};`
¡Excelente aporte, muchas gracias!
Lo apliqué con VueJS y quedó a la perfección con unos cuantos ajustes.
https://www.npmjs.com/package/numeros_a_letras
Este pakete que les paso lo hice yo, ya esta como reporitorio de npm
npm i numeros_a_letras
Espero les sirva
justo lo que buscaba, gracias, te ganaste mis gratitudes y mi estrella
para convertir de decimal a hexadecimal alguien me puede ayudar
El código original me pareció muy bien.
Lo he modificado con las siguientes características:
- Acepta hasta Centenas de Millones.
- Muestra una línea por default si la cifra es demasiado grande.
- Le añadí un filtro para que elimine signos o símbolos en el número recibido.
- Añadí un parámetro para mostrar la moneda (opcional)
- Y finalmente arreglé algunos errores de formato (espacios de más o de menos).
Lo he estado actualizando constantemente. Pueden revisar la efectividad de esta versión implementada en este generador de Pagarés.
const centavosFormatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
/**
* Función para convertir un número a letras, con centavos (ideal para representar dinero). Fuente: https://gist.github.com/alfchee/e563340276f89b22042a
*
* @param {float} cantidad - La cantidad a convertir en letras.
* @param {string} moneda - Moneda opcional para desplegarse en el texto si es que se especifica una. Ej: "PESOS", "DÓLARES"
*
* NumeroALetras
* The MIT License (MIT)
*
* Copyright (c) 2015 Luis Alfredo Chee
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author Rodolfo Carmona
* @contributor Jean (jpbadoino@gmail.com)
*
*/
function numeroALetras(cantidad, moneda) {
var numero = 0;
cantidad = filterNum(cantidad);
cantidad = parseFloat(cantidad);
if (cantidad == "0.00" || cantidad == "0") {
return "CERO 00/100 ";
} else {
var cantidadConCentavosExplicitos = centavosFormatter.format(parseFloat(cantidad)).toString().split(".");
var ent = cantidad.toString().split(".");
var arreglo = separar_split(ent[0]);
var longitud = arreglo.length;
switch (longitud) {
case 1:
numero = unidades(arreglo[0]);
break;
case 2:
numero = decenas(arreglo[0], arreglo[1]);
break;
case 3:
numero = centenas(arreglo[0], arreglo[1], arreglo[2]);
break;
case 4:
numero = unidadesdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3]);
break;
case 5:
numero = decenasdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4]);
break;
case 6:
numero = centenasdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5]);
break;
case 7:
numero = unidadesdemillon(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5], arreglo[6]);
break;
case 8:
numero = decenasdemillon(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5], arreglo[6], arreglo[7]);
break;
case 9:
numero = centenasdemillon(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5], arreglo[6], arreglo[7], arreglo[8]);
break;
default:
numero = "______________________________________________________________________";
break;
}
cantidadConCentavosExplicitos[1] = isNaN(cantidadConCentavosExplicitos[1]) ? '00' : cantidadConCentavosExplicitos[1];
if (cantidad == "1000000" && numero == "UN MILLÓN MIL ") {
numero = "UN MILLÓN ";
}
var divisibleEntreUnMillon = parseInt(cantidad) % 1000000;
if (divisibleEntreUnMillon == 0) {
numero = numero.replace("MILLONES MIL", "MILLONES");
}
if (moneda) {
if (cantidad == "1000000" && numero == "UN MILLÓN ") {
numero = "UN MILLÓN DE";
}
if (divisibleEntreUnMillon == 0 && parseInt(cantidad) > 1000000) {
numero = numero.replace("MILLONES", "MILLONES DE");
}
return numero + " " + moneda + " " + cantidadConCentavosExplicitos[1] + "/100";
} else {
return numero + cantidadConCentavosExplicitos[1] + "/100";
}
}
}
const filterNum = (str) => {
const numericalChar = new Set([".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]);
str = str.split("").filter(char => numericalChar.has(char)).join("");
return str;
}
function unidades(unidad) {
var unidades = Array('UN ', 'DOS ', 'TRES ', 'CUATRO ', 'CINCO ', 'SEIS ', 'SIETE ', 'OCHO ', 'NUEVE ');
return unidades[unidad - 1];
}
function decenas(decena, unidad) {
var diez = Array('ONCE ', 'DOCE ', 'TRECE ', 'CATORCE ', 'QUINCE', 'DIECISEIS ', 'DIECISIETE ', 'DIECIOCHO ', 'DIECINUEVE ');
var decenas = Array('DIEZ ', 'VEINTE', 'TREINTA', 'CUARENTA', 'CINCUENTA', 'SESENTA', 'SETENTA', 'OCHENTA', 'NOVENTA');
if (decena == 0 && unidad == 0) {
return "";
}
if (decena == 0 && unidad > 0) {
return unidades(unidad);
}
if (decena == 1) {
if (unidad == 0) {
return decenas[decena - 1];
} else {
return diez[unidad - 1];
}
} else if (decena == 2) {
if (unidad == 0) {
return decenas[decena - 1];
}
else if (unidad == 1) {
return veinte = "VEINTI" + "UNO ";
}
else {
return veinte = "VEINTI" + unidades(unidad);
}
} else {
if (unidad == 0) {
return decenas[decena - 1] + " ";
}
if (unidad == 1) {
return decenas[decena - 1] + " Y " + "UNO ";
}
return decenas[decena - 1] + " Y " + unidades(unidad);
}
}
function centenas(centena, decena, unidad) {
var centenas = Array("CIENTO ", "DOSCIENTOS ", "TRESCIENTOS ", "CUATROCIENTOS ", "QUINIENTOS ", "SEISCIENTOS ", "SETECIENTOS ", "OCHOCIENTOS ", "NOVECIENTOS ");
if (centena == 0 && decena == 0 && unidad == 0) {
return "";
}
if (centena == 1 && decena == 0 && unidad == 0) {
return "CIEN ";
}
if (centena == 0 && decena == 0 && unidad > 0) {
return unidades(unidad);
}
if (decena == 0 && unidad == 0) {
return centenas[centena - 1] + "";
}
if (decena == 0) {
var numero = centenas[centena - 1] + "" + decenas(decena, unidad);
return numero.replace(" Y ", " ");
}
if (centena == 0) {
return decenas(decena, unidad);
}
return centenas[centena - 1] + "" + decenas(decena, unidad);
}
function unidadesdemillar(unimill, centena, decena, unidad) {
var numero = unidades(unimill) + "MIL " + centenas(centena, decena, unidad);
numero = numero.replace("UN MIL ", "MIL ");
if (unidad == 0) {
return numero.replace(" Y ", " ");
} else {
return numero;
}
}
function decenasdemillar(decemill, unimill, centena, decena, unidad) {
var numero = decenas(decemill, unimill) + "MIL " + centenas(centena, decena, unidad);
return numero;
}
function centenasdemillar(centenamill, decemill, unimill, centena, decena, unidad) {
var numero = 0;
numero = centenas(centenamill, decemill, unimill) + "MIL " + centenas(centena, decena, unidad);
return numero;
}
function unidadesdemillon(unimillon, centenamill, decemill, unimill, centena, decena, unidad) {
var numero = unidades(unimillon) + "MILLONES " + centenas(centenamill, decemill, unimill) + "MIL " + centenas(centena, decena, unidad);
numero = numero.replace("UN MILLONES ", "UN MILLÓN ");
if (unidad == 0) {
return numero.replace(" Y ", " ");
} else {
return numero;
}
}
function decenasdemillon(decemillon, unimillon, centenamill, decemill, unimill, centena, decena, unidad) {
var numero = decenas(decemillon, unimillon) + "MILLONES " + centenas(centenamill, decemill, unimill) + "MIL " + centenas(centena, decena, unidad);
return numero;
}
function centenasdemillon(centenamillon, decemillon, unimillon, centenamill, decemill, unimill, centena, decena, unidad) {
var numero = 0;
numero = centenas(centenamillon, decemillon, unimillon) + "MILLONES " + centenas(centenamill, decemill, unimill) + "MIL " + centenas(centena, decena, unidad);
return numero;
}
function separar_split(texto) {
var contenido = new Array();
for (var i = 0; i < texto.length; i++) {
contenido[i] = texto.substr(i, 1);
}
return contenido;
}
Muchas gracias por el codigo, me sirvió!
Corregido sería así (los globales y los tokens de string):
var numeroALetras = (function() { // Código basado en https://gist.github.com/alfchee/e563340276f89b22042a function Unidades(num){ switch(num) { case 1: return 'UN'; case 2: return 'DOS'; case 3: return 'TRES'; case 4: return 'CUATRO'; case 5: return 'CINCO'; case 6: return 'SEIS'; case 7: return 'SIETE'; case 8: return 'OCHO'; case 9: return 'NUEVE'; } return ''; }//Unidades() function Decenas(num){ let decena = Math.floor(num/10); let unidad = num - (decena * 10); switch(decena) { case 1: switch(unidad) { case 0: return 'DIEZ'; case 1: return 'ONCE'; case 2: return 'DOCE'; case 3: return 'TRECE'; case 4: return 'CATORCE'; case 5: return 'QUINCE'; default: return 'DIECI' + Unidades(unidad); } case 2: switch(unidad) { case 0: return 'VEINTE'; default: return 'VEINTI' + Unidades(unidad); } case 3: return DecenasY('TREINTA', unidad); case 4: return DecenasY('CUARENTA', unidad); case 5: return DecenasY('CINCUENTA', unidad); case 6: return DecenasY('SESENTA', unidad); case 7: return DecenasY('SETENTA', unidad); case 8: return DecenasY('OCHENTA', unidad); case 9: return DecenasY('NOVENTA', unidad); case 0: return Unidades(unidad); } }//Unidades() function DecenasY(strSin, numUnidades) { if (numUnidades > 0) return strSin + ' Y ' + Unidades(numUnidades) return strSin; }//DecenasY() function Centenas(num) { let centenas = Math.floor(num / 100); let decenas = num - (centenas * 100); switch(centenas) { case 1: if (decenas > 0) return 'CIENTO ' + Decenas(decenas); return 'CIEN'; case 2: return 'DOSCIENTOS ' + Decenas(decenas); case 3: return 'TRESCIENTOS ' + Decenas(decenas); case 4: return 'CUATROCIENTOS ' + Decenas(decenas); case 5: return 'QUINIENTOS ' + Decenas(decenas); case 6: return 'SEISCIENTOS ' + Decenas(decenas); case 7: return 'SETECIENTOS ' + Decenas(decenas); case 8: return 'OCHOCIENTOS ' + Decenas(decenas); case 9: return 'NOVECIENTOS ' + Decenas(decenas); } return Decenas(decenas); }//Centenas() function Seccion(num, divisor, strSingular, strPlural) { let cientos = Math.floor(num / divisor) let resto = num - (cientos * divisor) let letras = ''; if (cientos > 0) if (cientos > 1) letras = Centenas(cientos) + ' ' + strPlural; else letras = strSingular; if (resto > 0) letras += ''; return letras; }//Seccion() function Miles(num) { let divisor = 1000; let cientos = Math.floor(num / divisor) let resto = num - (cientos * divisor) let strMiles = Seccion(num, divisor, 'UN MIL', 'MIL'); let strCentenas = Centenas(resto); if(strMiles == '') return strCentenas; return strMiles + ' ' + strCentenas; }//Miles() function Millones(num) { let divisor = 1000000; let cientos = Math.floor(num / divisor) let resto = num - (cientos * divisor) let strMillones = Seccion(num, divisor, 'UN MILLON DE', 'MILLONES DE'); let strMiles = Miles(resto); if(strMillones == '') return strMiles; return strMillones + ' ' + strMiles; }//Millones() return function NumeroALetras(num, currency) { currency = currency || {}; let data = { numero: num, enteros: Math.floor(num), centavos: (((Math.round(num * 100)) - (Math.floor(num) * 100))), letrasCentavos: '', letrasMonedaPlural: currency.plural || 'PESOS CHILENOS',//'PESOS', 'Dólares', 'Bolívares', 'etcs' letrasMonedaSingular: currency.singular || 'PESO CHILENO', //'PESO', 'Dólar', 'Bolivar', 'etc' letrasMonedaCentavoPlural: currency.centPlural || 'CHIQUI PESOS CHILENOS', letrasMonedaCentavoSingular: currency.centSingular || 'CHIQUI PESO CHILENO' }; if (data.centavos > 0) { data.letrasCentavos = 'CON ' + (function () { if (data.centavos == 1) return Millones(data.centavos) + ' ' + data.letrasMonedaCentavoSingular; else return Millones(data.centavos) + ' ' + data.letrasMonedaCentavoPlural; })(); }; if(data.enteros == 0) return 'CERO ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos; if (data.enteros == 1) return Millones(data.enteros) + ' ' + data.letrasMonedaSingular + ' ' + data.letrasCentavos; else return Millones(data.enteros) + ' ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos; }; })(); // Modo de uso: 500,34 USD numeroALetras(500.34, { plural: 'dólares estadounidenses', singular: 'dólar estadounidense', centPlural: 'centavos', centSingular: 'centavo' });
excelente aporte, ya lo estoy usando, gracias!
excelente trabajo, gracias ...me ahorraron horas de trabajo..
Muchas gracias por el codigo y a todos los que colaboran
lo adapte para Mexico
//
// NumeroALetras
// The MIT License (MIT)
//
// Copyright (c) 2015 Luis Alfredo Chee
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// @author Rodolfo Carmona
// @contributor Jean (jpbadoino@gmail.com)
//espero que les sirva Samir pazo
//
function NumerosaLetras(cantidad) {
var numero = 0;
cantidad = parseFloat(cantidad);
if (cantidad == "0.00" || cantidad == "0") {
return "CERO PESOS CON 00/100 M.N.";
} else {
var ent = cantidad.toString().split(".");
var arreglo = separar_split(ent[0]);
var longitud = arreglo.length;
switch (longitud) {
case 1:
numero = unidades(arreglo[0]);
break;
case 2:
numero = decenas(arreglo[0], arreglo[1]);
break;
case 3:
numero = centenas(arreglo[0], arreglo[1], arreglo[2]);
break;
case 4:
numero = unidadesdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3]);
break;
case 5:
numero = decenasdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4]);
break;
case 6:
numero = centenasdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5]);
break;
}
ent[1] = isNaN(ent[1]) ? '00' : ent[1];
return numero + "PESOS CON " + ent[1] + "/100 M.N";
}
}
function unidades(unidad) {
var unidades = Array('UN ','DOS ','TRES ' ,'CUATRO ','CINCO ','SEIS ','SIETE ','OCHO ','NUEVE ');
return unidades[unidad - 1];
}
function decenas(decena, unidad) {
var diez = Array('ONCE ','DOCE ','TRECE ','CATORCE ','QUINCE' ,'DIECISEIS ','DIECISIETE ','DIECIOCHO ','DIECINUEVE ');
var decenas = Array('DIEZ ','VEINTE ','TREINTA ','CUARENTA ','CINCUENTA ','SESENTA ','SETENTA ','OCHENTA ','NOVENTA ');
if (decena ==0 && unidad == 0) {
return "";
}
if (decena == 0 && unidad > 0) {
return unidades(unidad);
}
if (decena == 1) {
if (unidad == 0) {
return decenas[decena -1];
} else {
return diez[unidad -1];
}
} else if (decena == 2) {
if (unidad == 0) {
return decenas[decena -1];
}
else if (unidad == 1) {
return veinte = "VEINTI" + "UN ";
}
else {
return veinte = "VEINTI" + unidades(unidad);
}
} else {
if (unidad == 0) {
return decenas[decena -1] + " ";
}
if (unidad == 1) {
return decenas[decena -1] + " Y " + "UNO";
}
return decenas[decena -1] + " Y " + unidades(unidad);
}
}
function centenas(centena, decena, unidad) {
var centenas = Array( "CIENTO ", "DOSCIENTOS ", "TRESCIENTOS ", "CUATROCIENTOS ","QUINIENTOS ","SEISCIENTOS ","SETECIENTOS ", "OCHOCIENTOS ","NOVECIENTOS ");
if (centena == 0 && decena == 0 && unidad == 0) {
return "";
}
if (centena == 1 && decena == 0 && unidad == 0) {
return "CIEN ";
}
if (centena == 0 && decena == 0 && unidad > 0) {
return unidades(unidad);
}
if (decena == 0 && unidad == 0) {
return centenas[centena - 1] + "" ;
}
if (decena == 0) {
var numero = centenas[centena - 1] + "" + decenas(decena, unidad);
return numero.replace(" Y ", " ");
}
if (centena == 0) {
return decenas(decena, unidad);
}
return centenas[centena - 1] + "" + decenas(decena, unidad);
}
function unidadesdemillar(unimill, centena, decena, unidad) {
var numero = unidades(unimill) + " MIL " + centenas(centena, decena, unidad);
numero = numero.replace("UN MIL ", "MIL " );
if (unidad == 0) {
return numero.replace(" Y ", " ");
} else {
return numero;
}
}
function decenasdemillar(decemill, unimill, centena, decena, unidad) {
var numero = decenas(decemill, unimill) + " MIL " + centenas(centena, decena, unidad);
return numero;
}
function centenasdemillar(centenamill,decemill, unimill, centena, decena, unidad) {
var numero = 0;
numero = centenas(centenamill,decemill, unimill) + " MIL " + centenas(centena, decena, unidad);
return numero;
}
function separar_split(texto){
var contenido = new Array();
for (var i = 0; i < texto.length; i++) {
contenido[i] = texto.substr(i,1);
}
return contenido;
}
Hola, alguien me puede ayudar?? no entiendo como es que tengo que hacer para que mi hoja de cálculos de google sheets ejecute este código... no se si hay que vincularlos de algún modo o qué... dejo datos de contacto por si alquien me quiere ayudar! WHATSAPP: +541131208576 - INSTAGRAM: _fede_rivero - MAIL: fede88_r@hotmail.com
@plumilla2 Me gustaría saber como puedo invocar la función desde una hoja de google sheets.
mi email es filiberto.duran@uniceba.edu.mx
Excelente aporte, me ha servido de mucho, muchas gracias @alfchee
He actualizado el script a TS, optimizado un poco y eliminado la parte de la "moneda" para los que sólo necesiten el número.
// Código basado en https://gist.github.com/alfchee/e563340276f89b22042a
export const numeroALetras = (num: number) => {
let data = {
numero: num,
enteros: Math.floor(num),
decimales: Math.round(num * 100) - Math.floor(num) * 100,
letrasDecimales: '',
}
if (data.decimales > 0) data.letrasDecimales = ' PUNTO ' + Millones(data.decimales)
if (data.enteros == 0) return 'CERO' + data.letrasDecimales
if (data.enteros == 1) return Millones(data.enteros) + data.letrasDecimales
else return Millones(data.enteros) + data.letrasDecimales
}
const Unidades = (num: number) => {
const aLetras = {
1: 'UNO',
2: 'DOS',
3: 'TRES',
4: 'CUATRO',
5: 'CINCO',
6: 'SEIS',
7: 'SIETE',
8: 'OCHO',
9: 'NUEVE',
}
return aLetras[num] || ''
} // Unidades()
const Decenas = (num: number) => {
let decena = Math.floor(num / 10)
let unidad = num - decena * 10
const aLetras = {
1: (() => {
const aLetra = {
0: 'DIEZ',
1: 'ONCE',
2: 'DOCE',
3: 'TRECE',
4: 'CATORCE',
5: 'QUINCE',
}
return aLetra[unidad] || 'DIECI' + Unidades(unidad)
})(),
2: unidad == 0 ? 'VEINTE' : 'VEINTI' + Unidades(unidad),
3: DecenasY('TREINTA', unidad),
4: DecenasY('CUARENTA', unidad),
5: DecenasY('CINCUENTA', unidad),
6: DecenasY('SESENTA', unidad),
7: DecenasY('SETENTA', unidad),
8: DecenasY('OCHENTA', unidad),
9: DecenasY('NOVENTA', unidad),
0: Unidades(unidad),
}
return aLetras[decena] || ''
} //Decenas()
const DecenasY = (strSin: string, numUnidades: number) => {
if (numUnidades > 0) return strSin + ' Y ' + Unidades(numUnidades)
return strSin
} //DecenasY()
const Centenas = (num: number) => {
let centenas = Math.floor(num / 100)
let decenas = num - centenas * 100
const aLetras = {
1: decenas > 0 ? 'CIENTO ' + Decenas(decenas) : 'CIEN',
2: 'DOSCIENTOS ' + Decenas(decenas),
3: 'TRESCIENTOS ' + Decenas(decenas),
4: 'CUATROCIENTOS ' + Decenas(decenas),
5: 'QUINIENTOS ' + Decenas(decenas),
6: 'SEISCIENTOS ' + Decenas(decenas),
7: 'SETECIENTOS ' + Decenas(decenas),
8: 'OCHOCIENTOS ' + Decenas(decenas),
9: 'NOVECIENTOS ' + Decenas(decenas),
}
return aLetras[centenas] || Decenas(decenas)
} //Centenas()
const Seccion = (num: number, divisor: number, strSingular: string, strPlural: string) => {
let cientos = Math.floor(num / divisor)
let resto = num - cientos * divisor
let letras = ''
if (cientos > 0)
if (cientos > 1) letras = Centenas(cientos) + ' ' + strPlural
else letras = strSingular
if (resto > 0) letras += ''
return letras
} //Seccion()
const Miles = (num: number) => {
let divisor = 1000
let cientos = Math.floor(num / divisor)
let resto = num - cientos * divisor
let strMiles = Seccion(num, divisor, 'UN MIL', 'MIL')
let strCentenas = Centenas(resto)
if (strMiles == '') return strCentenas
return strMiles + ' ' + strCentenas
} //Miles()
const Millones = (num: number) => {
let divisor = 1000000
let cientos = Math.floor(num / divisor)
let resto = num - cientos * divisor
let strMillones = Seccion(num, divisor, 'UN MILLON DE', 'MILLONES DE')
let strMiles = Miles(resto)
if (strMillones == '') return strMiles
return strMillones + ' ' + strMiles
} //Millones()
console.log(numeroALetras(651.413))
// Expected: SEISCIENTOS CINCUENTA Y UNO PUNTO CUARENTA Y UNO
Yissela
El compartido es una contribución a las aportaciones de @benjamingranados, y @plumilla2.
- Formato de centavos
- Entrada es string que filtra por los números y el punto.
- Hasta centenas de millones
- El default "______ "
De @plumilla2,
- Adaptaciones a México. (PESOS CON ##/100 M.N al final. )
Nuevo
- UN PESOS y UN MIL PESOS se transforman en UN PESO y MIL PESOS por un condicional final.
- UN en vez de UNO siempre.
- Las sutilezas de UN MILLON (DE), y MILLONES (DE) se incluyen en las funciones unidades/decenas/centenas demillon.
- Funciones auxiliares son anidadas a la principal.
Aquí va:
const centavosFormatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
const filterNum = (str) => {
const numericalChar = new Set([".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]);
str = str.split("").filter(char => numericalChar.has(char)).join("");
return str;
}
/**
* Función para convertir un número a letras, con centavos (ideal para representar dinero). Fuente: https://gist.github.com/alfchee/e563340276f89b22042a
*
* @param {string} cantidad - La cantidad a convertir en letras.
*
* NumeroALetras
* The MIT License (MIT)
*
* Copyright (c) 2015 Luis Alfredo Chee
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author Rodolfo Carmona
* @contributor Jean (jpbadoino@gmail.com)
*
*/
function numeroALetras(cantidad) {
var numero = 0;
cantidad = filterNum(cantidad);
cantidad = parseFloat(cantidad);
if (cantidad == "0.00" || cantidad == "0") {
return "CERO PESOS CON 00/100 M.N.";
} else {
var ent = cantidad.toString().split(".");
var arreglo = separar_split(ent[0]);
var longitud = arreglo.length;
switch (longitud) {
case 1:
numero = unidades(arreglo[0]);
break;
case 2:
numero = decenas(arreglo[0], arreglo[1]);
break;
case 3:
numero = centenas(arreglo[0], arreglo[1], arreglo[2]);
break;
case 4:
numero = unidadesdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3]);
break;
case 5:
numero = decenasdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4]);
break;
case 6:
numero = centenasdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5]);
break;
case 7:
numero = unidadesdemillon(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5], arreglo[6]);
break;
case 8:
numero = decenasdemillon(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5], arreglo[6], arreglo[7]);
break;
case 9:
numero = centenasdemillon(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5], arreglo[6], arreglo[7], arreglo[8]);
break;
default:
numero = "_____________________________________________________________________ ";
break;
}
ent = centavosFormatter.format(parseFloat(cantidad)).toString().split(".");
ent[1] = isNaN(ent[1]) ? '00' : ent[1];
if (numero == 'UN '){
return "UN PESO CON " + ent[1] + "/100 M.N.";
}
if (numero == 'UN MIL'){
return "MIL PESOS CON " + ent[1] + "/100 M.N.";
}
return numero + "PESOS CON " + ent[1] + "/100 M.N.";
}
function unidades(unidad) {
var unidades = Array('UN ', 'DOS ', 'TRES ', 'CUATRO ', 'CINCO ', 'SEIS ', 'SIETE ', 'OCHO ', 'NUEVE ');
return unidades[unidad - 1];
}
function decenas(decena, unidad) {
var diez = Array('ONCE ', 'DOCE ', 'TRECE ', 'CATORCE ', 'QUINCE ', 'DIECISEIS ', 'DIECISIETE ', 'DIECIOCHO ', 'DIECINUEVE ');
var decenas = Array('DIEZ ', 'VEINTE ', 'TREINTA', 'CUARENTA', 'CINCUENTA', 'SESENTA', 'SETENTA', 'OCHENTA', 'NOVENTA');
if (decena == 0 && unidad == 0) {
return "";
}
if (decena == 0 && unidad > 0) {
return unidades(unidad);
}
if (decena == 1) {
if (unidad == 0) {
return decenas[decena - 1];
} else {
return diez[unidad - 1];
}
} else if (decena == 2) {
if (unidad == 0) {
return decenas[decena - 1];
}
else if (unidad == 1) {
return veinte = "VEINTI" + "UN ";
}
else {
return veinte = "VEINTI" + unidades(unidad);
}
} else {
if (unidad == 0) {
return decenas[decena - 1] + " ";
}
if (unidad == 1) {
return decenas[decena - 1] + " Y " + "UN ";
}
return decenas[decena - 1] + " Y " + unidades(unidad);
}
}
function centenas(centena, decena, unidad) {
var centenas = Array("CIENTO ", "DOSCIENTOS ", "TRESCIENTOS ", "CUATROCIENTOS ", "QUINIENTOS ", "SEISCIENTOS ", "SETECIENTOS ", "OCHOCIENTOS ", "NOVECIENTOS ");
if (centena == 0 && decena == 0 && unidad == 0) {
return "";
}
if (centena == 1 && decena == 0 && unidad == 0) {
return "CIEN ";
}
if (centena == 0 && decena == 0 && unidad > 0) {
return unidades(unidad);
}
if (decena == 0 && unidad == 0) {
return centenas[centena - 1] + "";
}
if (decena == 0) {
var numero = centenas[centena - 1] + "" + decenas(decena, unidad);
return numero.replace(" Y ", " ");
}
if (centena == 0) {
return decenas(decena, unidad);
}
return centenas[centena - 1] + "" + decenas(decena, unidad);
}
function unidadesdemillar(unimill, centena, decena, unidad) {
var numero = unidades(unimill) + "MIL " + centenas(centena, decena, unidad);
numero = numero.replace("UN MIL ", "MIL ");
if (unidad == 0) {
return numero.replace(" Y ", " ");
} else {
return numero;
}
}
function decenasdemillar(decemill, unimill, centena, decena, unidad) {
var numero = decenas(decemill, unimill) + "MIL " + centenas(centena, decena, unidad);
return numero;
}
function centenasdemillar(centenamill, decemill, unimill, centena, decena, unidad) {
var numero = 0;
numero = centenas(centenamill, decemill, unimill) + "MIL " + centenas(centena, decena, unidad);
return numero;
}
function unidadesdemillon(unimillon, centenamill, decemill, unimill, centena, decena, unidad) {
var centenasDeMillar = centenasdemillar(centenamill, decemill, unimill, centena, decena, unidad);
if (centenasDeMillar == "MIL ") {centenasDeMillar = "DE "};
if (unimillon == 1){
var numero = unidades(unimillon) + "MILLON " + centenasDeMillar;
} else {
var numero = unidades(unimillon) + "MILLONES " + centenasDeMillar;
}
if (unidad == 0) {
return numero.replace(" Y ", " ");
} else {
return numero;
}
}
function decenasdemillon(decemillon, unimillon, centenamill, decemill, unimill, centena, decena, unidad) {
var centenasDeMillar = centenasdemillar(centenamill, decemill, unimill, centena, decena, unidad);
if (centenasDeMillar == "MIL ") { centenasDeMillar = "DE "};
var numero = decenas(decemillon, unimillon) + "MILLONES " + centenasDeMillar;
return numero;
}
function centenasdemillon(centenamillon, decemillon, unimillon, centenamill, decemill, unimill, centena, decena, unidad) {
var centenasDeMillar = centenasdemillar(centenamill, decemill, unimill, centena, decena, unidad);
if (centenasDeMillar == "MIL ") { centenasDeMillar = "DE "};
var numero = centenas(centenamillon, decemillon, unimillon) + "MILLONES " + centenasDeMillar;
return numero;
}
function separar_split(texto) {
var contenido = new Array();
for (var i = 0; i < texto.length; i++) {
contenido[i] = texto.substr(i, 1);
}
return contenido;
}
}
Muchas gracias por el codigo y a todos los que colaboran
lo adapte para Mexico
// // NumeroALetras // The MIT License (MIT) // // Copyright (c) 2015 Luis Alfredo Chee // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // @author Rodolfo Carmona // @contributor Jean (jpbadoino@gmail.com) //espero que les sirva Samir pazo //
function NumerosaLetras(cantidad) {
var numero = 0; cantidad = parseFloat(cantidad); if (cantidad == "0.00" || cantidad == "0") { return "CERO PESOS CON 00/100 M.N."; } else { var ent = cantidad.toString().split("."); var arreglo = separar_split(ent[0]); var longitud = arreglo.length; switch (longitud) { case 1: numero = unidades(arreglo[0]); break; case 2: numero = decenas(arreglo[0], arreglo[1]); break; case 3: numero = centenas(arreglo[0], arreglo[1], arreglo[2]); break; case 4: numero = unidadesdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3]); break; case 5: numero = decenasdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4]); break; case 6: numero = centenasdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5]); break; } ent[1] = isNaN(ent[1]) ? '00' : ent[1]; return numero + "PESOS CON " + ent[1] + "/100 M.N"; }
}
function unidades(unidad) { var unidades = Array('UN ','DOS ','TRES ' ,'CUATRO ','CINCO ','SEIS ','SIETE ','OCHO ','NUEVE ');
return unidades[unidad - 1];
}
function decenas(decena, unidad) { var diez = Array('ONCE ','DOCE ','TRECE ','CATORCE ','QUINCE' ,'DIECISEIS ','DIECISIETE ','DIECIOCHO ','DIECINUEVE '); var decenas = Array('DIEZ ','VEINTE ','TREINTA ','CUARENTA ','CINCUENTA ','SESENTA ','SETENTA ','OCHENTA ','NOVENTA ');
if (decena ==0 && unidad == 0) { return ""; } if (decena == 0 && unidad > 0) { return unidades(unidad); } if (decena == 1) { if (unidad == 0) { return decenas[decena -1]; } else { return diez[unidad -1]; } } else if (decena == 2) { if (unidad == 0) { return decenas[decena -1]; } else if (unidad == 1) { return veinte = "VEINTI" + "UN "; } else { return veinte = "VEINTI" + unidades(unidad); } } else { if (unidad == 0) { return decenas[decena -1] + " "; } if (unidad == 1) { return decenas[decena -1] + " Y " + "UNO"; } return decenas[decena -1] + " Y " + unidades(unidad); }
}
function centenas(centena, decena, unidad) { var centenas = Array( "CIENTO ", "DOSCIENTOS ", "TRESCIENTOS ", "CUATROCIENTOS ","QUINIENTOS ","SEISCIENTOS ","SETECIENTOS ", "OCHOCIENTOS ","NOVECIENTOS ");
if (centena == 0 && decena == 0 && unidad == 0) { return ""; } if (centena == 1 && decena == 0 && unidad == 0) { return "CIEN "; } if (centena == 0 && decena == 0 && unidad > 0) { return unidades(unidad); } if (decena == 0 && unidad == 0) { return centenas[centena - 1] + "" ; } if (decena == 0) { var numero = centenas[centena - 1] + "" + decenas(decena, unidad); return numero.replace(" Y ", " "); } if (centena == 0) { return decenas(decena, unidad); } return centenas[centena - 1] + "" + decenas(decena, unidad);
}
function unidadesdemillar(unimill, centena, decena, unidad) { var numero = unidades(unimill) + " MIL " + centenas(centena, decena, unidad); numero = numero.replace("UN MIL ", "MIL " ); if (unidad == 0) { return numero.replace(" Y ", " "); } else { return numero; } }
function decenasdemillar(decemill, unimill, centena, decena, unidad) { var numero = decenas(decemill, unimill) + " MIL " + centenas(centena, decena, unidad); return numero; }
function centenasdemillar(centenamill,decemill, unimill, centena, decena, unidad) {
var numero = 0; numero = centenas(centenamill,decemill, unimill) + " MIL " + centenas(centena, decena, unidad); return numero;
}
function separar_split(texto){ var contenido = new Array(); for (var i = 0; i < texto.length; i++) { contenido[i] = texto.substr(i,1); } return contenido; }
Excelente! Me ayudó un buen tu aporte. Gracias!!
Muchas gracias por el código, me ayudo en mi momento más crítico.
El compartido es una contribución a las aportaciones de @benjamingranados, y @plumilla2.
- Formato de centavos
- Entrada es string que filtra por los números y el punto.
- Hasta centenas de millones
- El default "______ "
De @plumilla2,
- Adaptaciones a México. (PESOS CON ##/100 M.N al final. )
Nuevo
- UN PESOS y UN MIL PESOS se transforman en UN PESO y MIL PESOS por un condicional final.
- UN en vez de UNO siempre.
- Las sutilezas de UN MILLON (DE), y MILLONES (DE) se incluyen en las funciones unidades/decenas/centenas demillon.
- Funciones auxiliares son anidadas a la principal.
Aquí va:
const centavosFormatter = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); const filterNum = (str) => { const numericalChar = new Set([".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]); str = str.split("").filter(char => numericalChar.has(char)).join(""); return str; } /** * Función para convertir un número a letras, con centavos (ideal para representar dinero). Fuente: https://gist.github.com/alfchee/e563340276f89b22042a * * @param {string} cantidad - La cantidad a convertir en letras. * * NumeroALetras * The MIT License (MIT) * * Copyright (c) 2015 Luis Alfredo Chee * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * @author Rodolfo Carmona * @contributor Jean (jpbadoino@gmail.com) * */ function numeroALetras(cantidad) { var numero = 0; cantidad = filterNum(cantidad); cantidad = parseFloat(cantidad); if (cantidad == "0.00" || cantidad == "0") { return "CERO PESOS CON 00/100 M.N."; } else { var ent = cantidad.toString().split("."); var arreglo = separar_split(ent[0]); var longitud = arreglo.length; switch (longitud) { case 1: numero = unidades(arreglo[0]); break; case 2: numero = decenas(arreglo[0], arreglo[1]); break; case 3: numero = centenas(arreglo[0], arreglo[1], arreglo[2]); break; case 4: numero = unidadesdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3]); break; case 5: numero = decenasdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4]); break; case 6: numero = centenasdemillar(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5]); break; case 7: numero = unidadesdemillon(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5], arreglo[6]); break; case 8: numero = decenasdemillon(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5], arreglo[6], arreglo[7]); break; case 9: numero = centenasdemillon(arreglo[0], arreglo[1], arreglo[2], arreglo[3], arreglo[4], arreglo[5], arreglo[6], arreglo[7], arreglo[8]); break; default: numero = "_____________________________________________________________________ "; break; } ent = centavosFormatter.format(parseFloat(cantidad)).toString().split("."); ent[1] = isNaN(ent[1]) ? '00' : ent[1]; if (numero == 'UN '){ return "UN PESO CON " + ent[1] + "/100 M.N."; } if (numero == 'UN MIL'){ return "MIL PESOS CON " + ent[1] + "/100 M.N."; } return numero + "PESOS CON " + ent[1] + "/100 M.N."; } function unidades(unidad) { var unidades = Array('UN ', 'DOS ', 'TRES ', 'CUATRO ', 'CINCO ', 'SEIS ', 'SIETE ', 'OCHO ', 'NUEVE '); return unidades[unidad - 1]; } function decenas(decena, unidad) { var diez = Array('ONCE ', 'DOCE ', 'TRECE ', 'CATORCE ', 'QUINCE ', 'DIECISEIS ', 'DIECISIETE ', 'DIECIOCHO ', 'DIECINUEVE '); var decenas = Array('DIEZ ', 'VEINTE ', 'TREINTA', 'CUARENTA', 'CINCUENTA', 'SESENTA', 'SETENTA', 'OCHENTA', 'NOVENTA'); if (decena == 0 && unidad == 0) { return ""; } if (decena == 0 && unidad > 0) { return unidades(unidad); } if (decena == 1) { if (unidad == 0) { return decenas[decena - 1]; } else { return diez[unidad - 1]; } } else if (decena == 2) { if (unidad == 0) { return decenas[decena - 1]; } else if (unidad == 1) { return veinte = "VEINTI" + "UN "; } else { return veinte = "VEINTI" + unidades(unidad); } } else { if (unidad == 0) { return decenas[decena - 1] + " "; } if (unidad == 1) { return decenas[decena - 1] + " Y " + "UN "; } return decenas[decena - 1] + " Y " + unidades(unidad); } } function centenas(centena, decena, unidad) { var centenas = Array("CIENTO ", "DOSCIENTOS ", "TRESCIENTOS ", "CUATROCIENTOS ", "QUINIENTOS ", "SEISCIENTOS ", "SETECIENTOS ", "OCHOCIENTOS ", "NOVECIENTOS "); if (centena == 0 && decena == 0 && unidad == 0) { return ""; } if (centena == 1 && decena == 0 && unidad == 0) { return "CIEN "; } if (centena == 0 && decena == 0 && unidad > 0) { return unidades(unidad); } if (decena == 0 && unidad == 0) { return centenas[centena - 1] + ""; } if (decena == 0) { var numero = centenas[centena - 1] + "" + decenas(decena, unidad); return numero.replace(" Y ", " "); } if (centena == 0) { return decenas(decena, unidad); } return centenas[centena - 1] + "" + decenas(decena, unidad); } function unidadesdemillar(unimill, centena, decena, unidad) { var numero = unidades(unimill) + "MIL " + centenas(centena, decena, unidad); numero = numero.replace("UN MIL ", "MIL "); if (unidad == 0) { return numero.replace(" Y ", " "); } else { return numero; } } function decenasdemillar(decemill, unimill, centena, decena, unidad) { var numero = decenas(decemill, unimill) + "MIL " + centenas(centena, decena, unidad); return numero; } function centenasdemillar(centenamill, decemill, unimill, centena, decena, unidad) { var numero = 0; numero = centenas(centenamill, decemill, unimill) + "MIL " + centenas(centena, decena, unidad); return numero; } function unidadesdemillon(unimillon, centenamill, decemill, unimill, centena, decena, unidad) { var centenasDeMillar = centenasdemillar(centenamill, decemill, unimill, centena, decena, unidad); if (centenasDeMillar == "MIL ") {centenasDeMillar = "DE "}; if (unimillon == 1){ var numero = unidades(unimillon) + "MILLON " + centenasDeMillar; } else { var numero = unidades(unimillon) + "MILLONES " + centenasDeMillar; } if (unidad == 0) { return numero.replace(" Y ", " "); } else { return numero; } } function decenasdemillon(decemillon, unimillon, centenamill, decemill, unimill, centena, decena, unidad) { var centenasDeMillar = centenasdemillar(centenamill, decemill, unimill, centena, decena, unidad); if (centenasDeMillar == "MIL ") { centenasDeMillar = "DE "}; var numero = decenas(decemillon, unimillon) + "MILLONES " + centenasDeMillar; return numero; } function centenasdemillon(centenamillon, decemillon, unimillon, centenamill, decemill, unimill, centena, decena, unidad) { var centenasDeMillar = centenasdemillar(centenamill, decemill, unimill, centena, decena, unidad); if (centenasDeMillar == "MIL ") { centenasDeMillar = "DE "}; var numero = centenas(centenamillon, decemillon, unimillon) + "MILLONES " + centenasDeMillar; return numero; } function separar_split(texto) { var contenido = new Array(); for (var i = 0; i < texto.length; i++) { contenido[i] = texto.substr(i, 1); } return contenido; } }
Hice un pequeño cambio por si alguien necesita que diga "CENTAVOS" en vez de "00/100 M.N", que no es muy comun pero podria servir para algo menos formal
`ent = centavosFormatter.format(parseFloat(cantidad)).toString().split(".");
ent[1] = isNaN(ent[1]) ? '00' : ent[1];
var arreglo_centavos = separar_split(ent[1]);
var longitud_centavos = arreglo_centavos.length;
if (numero == 'UN '){
switch (longitud_centavos) {
case 1:
numero_centavos = unidades(arreglo_centavos[0]);
break;
case 2:
numero_centavos = decenas(arreglo_centavos[0], arreglo_centavos[1]);
break;
default:
break;
}
return "UN PESO CON " + numero_centavos + " CENTAVOS";
}
if (numero == 'UN MIL'){
switch (longitud_centavos) {
case 1:
numero_centavos = unidades(arreglo_centavos[0]);
break;
case 2:
numero_centavos = decenas(arreglo_centavos[0], arreglo_centavos[1]);
break;
default:
break;
}
return "MIL PESOS CON " + numero_centavos + " CENTAVOS";
}
switch (longitud_centavos) {
case 1:
numero_centavos = unidades(arreglo_centavos[0]);
break;
case 2:
numero_centavos = decenas(arreglo_centavos[0], arreglo_centavos[1]);
break;
default:
break;
}
return numero + "PESOS CON " + numero_centavos + "CENTAVOS";
}`
// ¡Me ayudo! ¡gracias por el aporte! // para bolivianos (FACTURAS) pequeña modificación // numeroALetras(543.15) // QUINIENTOS CUARENTA Y TRES 15/100 BOLIVIANOS`
return function NumeroALetras(num, currency) { currency = currency || {}; let data = { numero: num, enteros: Math.floor(num), centavos: (((Math.round(num * 100)) - (Math.floor(num) * 100))), letrasCentavos: '', letrasMonedaPlural: currency.plural || 'BOLIVIANOS' // Solo usa el plural };
`data.letrasCentavos = ' ' + (function () { if (data.centavos > 9) return data.centavos + '/100 ' + data.letrasMonedaPlural; else return '0' + data.centavos + '/100 ' + data.letrasMonedaPlural; })(); if(data.enteros == 0) return 'CERO' + data.letrasCentavos; if (data.enteros == 1) return Millones(data.enteros) + data.letrasCentavos; else return Millones(data.enteros) + data.letrasCentavos; };
})(); `
Hola un favor puedes enviar el codigo completo por favor, muchas gracias!
Hola, por favor si alguien pudiera ayudarme, implemente el código original solo editando el nombre de mi moneda local y va de maravilla, el tema es que cuando el Script lee la celda con el número separado por punto ej: (20.54) arroja el resultado bien, pero si en la celda coloco ese mismo número o cualquiera otro separado por coma (20,54) la celda donde debe arrojar el resultado en letras dice (Undefined Bolívares), en mi caso las cifras deben ser en formato Latinoamericano (0,00) y no encuentro como resolverlo, la hoja de cálculo ya tiene formato Latinoamericano, y el proyecto en Apps Script en su configuración, también está definido mi país como región, por lo cual deduzco que debe estar en el código fuente el problema que lee bien con punto separador, pero no con coma, ojo no soy experto en programación y lenguaje, por eso solicito ayuda y agradezco de antemano quien pueda colaborar, aqui les dejo mi codigo tal cual lo tengo actualmente, gracias.-
//tomado de : https://gist.github.com/alfchee/e563340276f89b22042a
//*************************************************************/
// NumeroALetras
// The MIT License (MIT)
//
// Copyright (c) 2015 Luis Alfredo Chee
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// @author Rodolfo Carmona
// @contributor Jean (jpbadoino@gmail.com)
/*************************************************************/
function Unidades(num){
switch(num)
{
case 1: return "UN";
case 2: return "DOS";
case 3: return "TRES";
case 4: return "CUATRO";
case 5: return "CINCO";
case 6: return "SEIS";
case 7: return "SIETE";
case 8: return "OCHO";
case 9: return "NUEVE";
}
return "";
}//Unidades()
function Decenas(num){
decena = Math.floor(num/10);
unidad = num - (decena * 10);
switch(decena)
{
case 1:
switch(unidad)
{
case 0: return "DIEZ";
case 1: return "ONCE";
case 2: return "DOCE";
case 3: return "TRECE";
case 4: return "CATORCE";
case 5: return "QUINCE";
default: return "DIECI" + Unidades(unidad);
}
case 2:
switch(unidad)
{
case 0: return "VEINTE";
default: return "VEINTI" + Unidades(unidad);
}
case 3: return DecenasY("TREINTA", unidad);
case 4: return DecenasY("CUARENTA", unidad);
case 5: return DecenasY("CINCUENTA", unidad);
case 6: return DecenasY("SESENTA", unidad);
case 7: return DecenasY("SETENTA", unidad);
case 8: return DecenasY("OCHENTA", unidad);
case 9: return DecenasY("NOVENTA", unidad);
case 0: return Unidades(unidad);
}
}//Unidades()
function DecenasY(strSin, numUnidades) {
if (numUnidades > 0)
return strSin + " Y " + Unidades(numUnidades)
return strSin;
}//DecenasY()
function Centenas(num) {
centenas = Math.floor(num / 100);
decenas = num - (centenas * 100);
switch(centenas)
{
case 1:
if (decenas > 0)
return "CIENTO " + Decenas(decenas);
return "CIEN";
case 2: return "DOSCIENTOS " + Decenas(decenas);
case 3: return "TRESCIENTOS " + Decenas(decenas);
case 4: return "CUATROCIENTOS " + Decenas(decenas);
case 5: return "QUINIENTOS " + Decenas(decenas);
case 6: return "SEISCIENTOS " + Decenas(decenas);
case 7: return "SETECIENTOS " + Decenas(decenas);
case 8: return "OCHOCIENTOS " + Decenas(decenas);
case 9: return "NOVECIENTOS " + Decenas(decenas);
}
return Decenas(decenas);
}//Centenas()
function Seccion(num, divisor, strSingular, strPlural) {
cientos = Math.floor(num / divisor)
resto = num - (cientos * divisor)
letras = "";
if (cientos > 0)
if (cientos > 1)
letras = Centenas(cientos) + " " + strPlural;
else
letras = strSingular;
if (resto > 0)
letras += "";
return letras;
}//Seccion()
function Miles(num) {
divisor = 1000;
cientos = Math.floor(num / divisor)
resto = num - (cientos * divisor)
strMiles = Seccion(num, divisor, "UN MIL", "MIL");
strCentenas = Centenas(resto);
if(strMiles == "")
return strCentenas;
return strMiles + " " + strCentenas;
}//Miles()
function Millones(num) {
divisor = 1000000;
cientos = Math.floor(num / divisor)
resto = num - (cientos * divisor)
strMillones = Seccion(num, divisor, "UN MILLON DE", "MILLONES DE");
strMiles = Miles(resto);
if(strMillones == "")
return strMiles;
return strMillones + " " + strMiles;
}//Millones()
function NumeroALetrasBs(num) {
var data = {
numero: num,
enteros: Math.floor(num),
centavos: (((Math.round(num * 100)) - (Math.floor(num) * 100))),
letrasCentavos: "",
letrasMonedaPlural: 'Bolívares',//Córdobas, "PESOS", 'Dólares', 'Bolívares', 'etcs'
letrasMonedaSingular: 'Bolívar', //Córdoba, "PESO", 'Dólar', 'Bolivar', 'etc'
letrasMonedaCentavoPlural: "CENTIMOS",
letrasMonedaCentavoSingular: "CENTIMO"
};
if (data.centavos > 0) {
data.letrasCentavos = "CON " + (function (){
if (data.centavos == 1)
return Millones(data.centavos) + " " + data.letrasMonedaCentavoSingular;
else
return Millones(data.centavos) + " " + data.letrasMonedaCentavoPlural;
})();
};
if(data.enteros == 0)
return "CERO " + data.letrasMonedaPlural + " " + data.letrasCentavos;
if (data.enteros == 1)
return Millones(data.enteros) + " " + data.letrasMonedaSingular + " " + data.letrasCentavos;
else
return Millones(data.enteros) + " " + data.letrasMonedaPlural + " " + data.letrasCentavos;
}//NumeroALetrasBs()
SI DESEAS PARA TYPESCRIPT
import numeroALetras from "@vigilio/numeros-a-letras";
console.log(numeroALetras(1040.34)); // UN MIL CUARENTA CON TREINTA Y CUATRO
console.log(numeroALetras(1040.34, true, { isInvoice: true })); // UN MIL CUARENTA SOLES 34/100 SOLES
console.log(
numeroALetras(1040.34, true, {
centPlural: "CENTAVOS",
centSingular: "CENTAVO",
Monedaplural: "PESOS",
Monedasingular: "PESO",
})
);
Señores.
El definitivo que funciona en las hojas de cálculo en Google Drive, metiendo el código en App Scripts.
- Este código no tiene en cuenta ninguna divisa o moneda, de ningún país. Es decir, vale para convertir a letra cualquier cifra. Poned luego vuestra moneda si lo necesitáis con Concatenar, por ejemplo.
- Se han depurado los espacios sobrantes entre palabras que venían mal en alguna de las propuestas anteriores.
- Usa correctamente el castellano para acentuar palabras como veintitrés, dieciséis, veintiún, etc.
- En los millares, cuando estos son uno (51.000), dirá «cincuenta y un mil», y no «cincuenta y uno mil». También funciona con [veintiún mil].
La función en la hoja de cálculo será igual:
numeroaletras(A1)
Espero que os valga.
function Unidades(num) {
switch(num) {
case 1: return 'uno';
case 2: return 'dos';
case 3: return 'tres';
case 4: return 'cuatro';
case 5: return 'cinco';
case 6: return 'seis';
case 7: return 'siete';
case 8: return 'ocho';
case 9: return 'nueve';
}
return '';
}
function Decenas(num) {
let decena = Math.floor(num / 10);
let unidad = num - (decena * 10);
switch(decena) {
case 1:
switch(unidad) {
case 0: return 'diez';
case 1: return 'once';
case 2: return 'doce';
case 3: return 'trece';
case 4: return 'catorce';
case 5: return 'quince';
default: return 'dieci' + Unidades(unidad);
}
case 2:
if(unidad == 0)
return 'veinte';
else
return 'veinti' + Unidades(unidad);
case 3: return DecenasY('treinta', unidad);
case 4: return DecenasY('cuarenta', unidad);
case 5: return DecenasY('cincuenta', unidad);
case 6: return DecenasY('sesenta', unidad);
case 7: return DecenasY('setenta', unidad);
case 8: return DecenasY('ochenta', unidad);
case 9: return DecenasY('noventa', unidad);
case 0: return Unidades(unidad);
}
}
function DecenasY(strSin, numUnidades) {
if (numUnidades > 0)
return strSin + ' y ' + Unidades(numUnidades);
return strSin;
}
function Centenas(num) {
let centenas = Math.floor(num / 100);
let decenas = num - (centenas * 100);
switch(centenas) {
case 1:
if (decenas > 0)
return 'ciento ' + Decenas(decenas);
return 'cien';
case 2: return 'doscientos ' + Decenas(decenas);
case 3: return 'trescientos ' + Decenas(decenas);
case 4: return 'cuatrocientos ' + Decenas(decenas);
case 5: return 'quinientos ' + Decenas(decenas);
case 6: return 'seiscientos ' + Decenas(decenas);
case 7: return 'setecientos ' + Decenas(decenas);
case 8: return 'ochocientos ' + Decenas(decenas);
case 9: return 'novecientos ' + Decenas(decenas);
}
return Decenas(decenas);
}
function Seccion(num, divisor, strSingular, strPlural) {
let cientos = Math.floor(num / divisor);
let resto = num - (cientos * divisor);
let letras = '';
if (cientos > 0)
if (cientos > 1)
letras = Centenas(cientos) + ' ' + strPlural;
else
letras = strSingular;
if (resto > 0)
letras += ' ';
return letras.trim(); // Eliminamos espacios al final
}
function Miles(num) {
let divisor = 1000;
let cientos = Math.floor(num / divisor);
let resto = num - (cientos * divisor);
let strMiles = Seccion(num, divisor, 'mil', 'mil');
let strCentenas = Centenas(resto);
if (cientos === 1) {
strMiles = 'mil';
} else if (cientos === 21) {
strMiles = 'veintiún mil';
} else if (cientos > 1) {
strMiles = Centenas(cientos).replace('uno', 'un') + ' mil';
}
if(strMiles === '')
return strCentenas;
return strMiles + ' ' + strCentenas;
}
function Millones(num) {
let divisor = 1000000;
let cientos = Math.floor(num / divisor);
let resto = num - (cientos * divisor);
let strMillones = Seccion(num, divisor, 'un millón', 'millones');
let strMiles = Miles(resto);
if(strMillones === '')
return strMiles;
return strMillones + ' ' + strMiles;
}
function NumeroALetras(num, currency) {
currency = currency || {};
let data = {
numero: num,
enteros: Math.floor(num),
centavos: (((Math.round(num * 100)) - (Math.floor(num) * 100))),
letrasCentavos: '',
letrasMonedaPlural: currency.plural || '',
letrasMonedaSingular: currency.singular || '',
letrasMonedaCentavoPlural: currency.centPlural || '',
letrasMonedaCentavoSingular: currency.centSingular || ''
};
if (data.centavos > 0) {
data.letrasCentavos = 'con ' + NumeroALetras(data.centavos).trim() + ' ' + (data.centavos === 1 ? data.letrasMonedaCentavoSingular : data.letrasMonedaCentavoPlural);
}
let letrasEnteros = Millones(data.enteros).trim();
letrasEnteros = letrasEnteros.replace('dieciseis', 'dieciséis');
letrasEnteros = letrasEnteros.replace('veintidos', 'veintidós');
letrasEnteros = letrasEnteros.replace('veintitres', 'veintitrés');
letrasEnteros = letrasEnteros.replace('veintiseis', 'veintiséis');
if(data.enteros === 0)
return 'cero ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos.trim();
if (data.enteros === 1)
return letrasEnteros + ' ' + data.letrasMonedaSingular + ' ' + data.letrasCentavos.trim();
else
return letrasEnteros + ' ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos.trim();
}
function convertirNumeroALetras(num) {
if (num === undefined || isNaN(num)) {
return '';
}
let partes = num.toString().split('.');
let enteros = parseInt(partes[0], 10);
let decimales = partes.length > 1 ? parseInt(partes[1].slice(0, 2), 10) : 0;
let letrasEnteros = NumeroALetras(enteros).trim(); // Usamos .trim() para eliminar espacios extra
let letrasDecimales = decimales > 0 ? `con ${NumeroALetras(decimales).trim()}` : '';
return `${letrasEnteros} ${letrasDecimales}`.trim();
}
// Función que se usará en la hoja de cálculo de Google
function numeroALetras(celda) {
return convertirNumeroALetras(celda);
}
Hola, para los que manejan angular 17
`import { Component, Input } from '@angular/core';
@component({
selector: 'app-numeros-letras',
standalone: true,
imports: [],
templateUrl: './numeros-letras.component.html',
styleUrl: './numeros-letras.component.css'
})
export class NumerosLetrasComponent {
@input() num: number = 0;
Unidades(num: number): string {
switch (num) {
case 1: return "UN";
case 2: return "DOS";
case 3: return "TRES";
case 4: return "CUATRO";
case 5: return "CINCO";
case 6: return "SEIS";
case 7: return "SIETE";
case 8: return "OCHO";
case 9: return "NUEVE";
}
return "";
}//Unidades()
Decenas(num: number): string | undefined {
let decena = Math.floor(num / 10);
let unidad = num - (decena * 10);
switch (decena) {
case 1:
switch (unidad) {
case 0: return "DIEZ";
case 1: return "ONCE";
case 2: return "DOCE";
case 3: return "TRECE";
case 4: return "CATORCE";
case 5: return "QUINCE";
default: return "DIECI" + this.Unidades(unidad);
}
case 2:
switch (unidad) {
case 0: return "VEINTE";
default: return "VEINTI" + this.Unidades(unidad);
}
case 3: return this.DecenasY("TREINTA", unidad);
case 4: return this.DecenasY("CUARENTA", unidad);
case 5: return this.DecenasY("CINCUENTA", unidad);
case 6: return this.DecenasY("SESENTA", unidad);
case 7: return this.DecenasY("SETENTA", unidad);
case 8: return this.DecenasY("OCHENTA", unidad);
case 9: return this.DecenasY("NOVENTA", unidad);
case 0: return this.Unidades(unidad);
}
}//Unidades()
DecenasY(strSin: string, numUnidades: number): string {
if (numUnidades > 0)
return strSin + " Y " + this.Unidades(numUnidades)
return strSin;
}//DecenasY()
Centenas(num: number): string | undefined {
let centenas = Math.floor(num / 100);
let decenas = num - (centenas * 100);
switch (centenas) {
case 1:
if (decenas > 0)
return "CIENTO " + this.Decenas(decenas);
return "CIEN";
case 2: return "DOSCIENTOS " + this.Decenas(decenas);
case 3: return "TRESCIENTOS " + this.Decenas(decenas);
case 4: return "CUATROCIENTOS " + this.Decenas(decenas);
case 5: return "QUINIENTOS " + this.Decenas(decenas);
case 6: return "SEISCIENTOS " + this.Decenas(decenas);
case 7: return "SETECIENTOS " + this.Decenas(decenas);
case 8: return "OCHOCIENTOS " + this.Decenas(decenas);
case 9: return "NOVECIENTOS " + this.Decenas(decenas);
}
return this.Decenas(decenas);
}//Centenas()
Seccion(num: number, divisor: number, strSingular: string, strPlural: string): string {
let cientos = Math.floor(num / divisor)
let resto = num - (cientos * divisor)
let letras = "";
if (cientos > 0)
if (cientos > 1)
letras = this.Centenas(cientos) + " " + strPlural;
else
letras = strSingular;
if (resto > 0)
letras += "";
return letras;
}//Seccion()
Miles(num: number): string | undefined {
let divisor = 1000;
let cientos = Math.floor(num / divisor)
let resto = num - (cientos * divisor)
let strMiles = this.Seccion(num, divisor, "UN MIL", "MIL");
let strCentenas = this.Centenas(resto);
if (strMiles == "")
return strCentenas;
return strMiles + " " + strCentenas;
}//Miles()
Millones(num: number): string | undefined {
let divisor = 1000000;
let cientos = Math.floor(num / divisor)
let resto = num - (cientos * divisor)
let strMillones = this.Seccion(num, divisor, "UN MILLON", "MILLONES");
let strMiles = this.Miles(resto);
if (strMillones == "")
return strMiles;
return strMillones + " " + strMiles;
}//Millones()
NumeroALetras(num: number): string {
var data = {
numero: num,
enteros: Math.floor(num),
centavos: (((Math.round(num * 100)) - (Math.floor(num) * 100))),
letrasCentavos: "",
letrasMonedaPlural: 'PESOS',//"PESOS", 'Dólares', 'Bolívares', 'etcs'
letrasMonedaSingular: 'PESO', //"PESO", 'Dólar', 'Bolivar', 'etc'
letrasMonedaCentavoPlural: "CENTAVOS",
letrasMonedaCentavoSingular: "CENTAVO"
}
if (data.centavos > 0) {
let centavos = ''
if (data.centavos == 1)
centavos = this.Millones(data.centavos) + ' ' + data.letrasMonedaCentavoSingular;
else
centavos = this.Millones(data.centavos) + ' ' + data.letrasMonedaCentavoPlural;
data.letrasCentavos = 'CON ' + centavos
};
if (data.enteros == 0)
return "CERO " + data.letrasMonedaPlural + " " + data.letrasCentavos;
if (data.enteros == 1)
return this.Millones(data.enteros) + " " + data.letrasMonedaSingular + " " + data.letrasCentavos;
else
return this.Millones(data.enteros) + " " + data.letrasMonedaPlural + " " + data.letrasCentavos;
}
}
`
Buen aporte