i made a simple program convert number to word. and i got problem when i want to convert minus number.
I want to find the index in the array 'satuan' so that later I add the word 'minus'
in my code i use Indonesian language btw.
js code:
// i have array like this
var satuan = ['', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan'];
// and my function to convert minus number like this
function convert_minesPuluhan(num) {
var c = Math.abs(num) + Math.abs(num);
if (num < 0 && num > -10) {
return satuan[num + c];
}
}
but when i console.log(num + c). the result is (example the num value is -1) -12.
but what I want is -1 + 1 + 1 = 1
// so i want like this
satuan[1];
how to solve this?
You are most likely getting a string for num
So, you'll have to do num = parseInt(num) first to convert it into an int datatype.
i.e.
function convert_minesPuluhan(num) {
num = parseInt(num)
var c = Math.abs(num) + Math.abs(num);
if (num < 0 && num > -10) {
return satuan[num + c];
}
}
Try this, your code is working fine. I understand that you need to add the 'minus' keyword before negative numbers.
var satuan = ['', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan'];
// and my function to convert minus number like this
function convert_minesPuluhan(num) {
var c = Math.abs(num) + Math.abs(num);
if (num < 0 && num > -10) {
console.log("minus " + satuan[num + c])
return "minus " + satuan[num + c];
}
}
convert_minesPuluhan(-5)
You need to convert the input of your function to integer
You are adding 2 strings in your function "-1" and "2" and thats why youre getting "-12" which is undefined.
let num = parseInt(num);
Try this inside your function and rest all is the same.
Related
I'm sorry for the dumb question. I've been trying to do this for hours now, and i really can't get it to work. So i have a for-loop that loops though some numbers.
But it doesn't take the first value(71990000).
How can this be achieved?
This is what i've got so far:
var minNr = 0000;
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max)
{
var regex = /^(\d{2})\1$/;
var guld_nr;
for(guld_nr = minNr; guld_nr < maxNr;)
{
if(regex.test(guld_nr))
{
$(".resultat").append(prefix + "" + guld_nr + "<br>");
}
guld_nr++;
}
}
The output is this:
71991010
71991111
71991212
71991313
But i also need the number: 71990000
How can i do that ?
It's because your regex is rejecting the number 0; the first time through the loop, minNr has the numeric value 0 (setting it to 0000 doesn't help; it's just a fancy way of saying 0). The regex expects two digits followed by the same pattern, but what you're giving it is the string '0'.
You could set minNr to be a string instead on the first pass through ('0000'), and this will solve the problem for '0000', but you will miss '0101', '0202', etc. (which will convert to the strings '101', '202', and so on.)
One solution would be to zero pad the string representation of your number. The following function will take any number and left zero pad it to fit a given width:
function zeropad(n, w) {
n = String(n);
while(n.length < w) n = '0' + n;
return n;
}
You can use it to convert minNr for the regex:
regex.test(zeropad(guld_nr, 4))
Also note that Number is a built-in object wrapper for literals in JavaScript (all of the primitives have object wrappers: Number, Boolean, String), and by creating a function called Number, you are occluding this built-in object, which is inadvisable (code that needs to use it will invoke your function instead, which is incompatible and has a different purpose).
Use string:
var minNr = '0000';
It's the start value for the regex test, and you need the four zeroes for that. If it would be a number, then you get only one zero for testing. it would help, if you pad it with leading zeroes.
var minNr = '0000',
maxNr = 10000,
prefix = 7199;
function Nummer(min,max) {
var regex = /^(\d{2})\1$/;
var guld_nr;
for(guld_nr = minNr; guld_nr < maxNr;guld_nr++) {
if(regex.test(guld_nr)) {
document.write(prefix + "" + guld_nr + "<br>");
}
}
}
Nummer(minNr, maxNr);
Numbers don't zero-pad themselves; 0000; // 0
Make a custom zero-pad method for it so you can do zpad(0, 4); // "0000"
function zpad(x, digits) {
var pad = '0';
x = x.toString();
digits -= x.length;
while (digits > 0) {
if (digits & 1) x = pad + x;
pad += pad;
digits >>>= 1;
}
return x;
}
Now adjust Nummer accordingly
function Nummer(min, max, prefix) {
var regex = /^(\d{2})\1$/,
i, str;
prefix = prefix || '';
for(i = min; i < max; ++i) {
str = zpad(i, 4);
if(regex.test(str)) console.log(prefix + str);
}
}
and use
Nummer(minNr, maxNr, '7199');
Side note
Nummer is not constructing an Object, consider camel casing it
You could use arithmetic to do the digit pattern check, and keep the result numerical:
var minNr = 0; // it does not help to put 4 zeroes here.
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max) {
for (var guld_nr = min; guld_nr < max; guld_nr++) {
if (Math.floor(guld_nr/100) === guld_nr % 100 ) {
$(".resultat").append((prefix * 10000 + guld_nr) + "<br>");
}
}
}
Nummer(minNr, maxNr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultat"></div>
The problem with your code is when the lower numbers are tested against the regular expression, they are implicitly converted to string, and do not get prefixed zeroes, so they fail on the regular expression.
Anyway, the code will be more efficient when sticking to numbers instead of strings, so I would suggest working with numbers all the way up to the point of outputting them in the browser.
Even more efficient is this code:
var minNr = 0; // it does not help to put 4 zeroes here.
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max) {
var test = Math.floor(min/100)*100 + Math.floor(min/100)%100;
var guld_nr = test < min ? test + 101 : test;
for (; guld_nr < max; guld_nr+=101) {
$(".resultat").append((prefix * 10000 + guld_nr) + "<br>");
}
}
Nummer(minNr, maxNr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultat"></div>
I'm using JQuery and I'm having a problem trying to sort out how to increase a number.
The record number is something like 1364-14-1234.
The number format works like this:
1364 - Member number
14 - Year in 2 digit format
1234 - in the number which needs to be increased.
The problem is how do I add a leading zero to the number to keep a 4 digit number if the number is 0123.
<div id="member_id">1364-14-0001</div>
var data = $('#member_id').text();
var arr = data.split('-');
var num = arr[2];
num++;
$("#member_id").html(arr[0] + " - " + arr[1] + " - " + num);
My JSfiddle
Something like this maybe
function pad(numb, len) {
while (numb.toString().length < len) numb = '0' + numb;
return numb;
}
$('#member_id').text(function(_, txt) {
var arr = txt.split('-'),
len = arr[2].length;
arr[2] = pad(+(arr[2]) + 1, len);
return arr.join('-')
});
FIDDLE
I'm trying to show numbers in labels. If the number > 1000 the format should look like
1.000 or 1,000
I tried with toFixed but it is not the solution, also toPrecision but it gave me a number like 1,2e+
I tried with
number/1000
but when the number ends up with a 0, it disappears from the result, so how can i do this??
I whipped up the following function. It will add a comma after 3 digits. Works on whole numbers.
function formatNumber(num)
{
var formattedNumber = "";
var numString = num.toString();
var numCount = 0;
for (var index = numString.length - 1; index >= 0; index--)
{
if (numCount % 3 == 0
&& numString[index] != '-'
&& formattedNumber)
{
formattedNumber = ',' + formattedNumber;
}
formattedNumber = numString[index] + formattedNumber;
numCount++;
}
return formattedNumber;
}
You would have to write your own function. Something like this:
http://www.mredkj.com/javascript/nfbasic.html
EDIT: Found the original code
var number = 1310;
should be left alone.
var number = 120;
should be changed to "0120";
var number = 10;
should be changed to "0010";
var number = 7;
should be changed to "0007";
In all modern browsers you can use
numberStr.padStart(4, "0");
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
function zeroPad(num) {
return num.toString().padStart(4, "0");
}
var numbers = [1310, 120, 10, 7];
numbers.forEach(
function(num) {
var paddedNum = zeroPad(num);
console.log(paddedNum);
}
);
function pad_with_zeroes(number, length) {
var my_string = '' + number;
while (my_string.length < length) {
my_string = '0' + my_string;
}
return my_string;
}
try these:
('0000' + number).slice(-4);
or
(number+'').padStart(4,'0');
Here's another way. Comes from something I did that needs to be done thousands of times on a page load. It's pretty CPU efficient to hard code a string of zeroes one time, and chop as many as you need for the pad as many times as needed. I do really like the power of 10 method -- that's pretty flexible.
Anyway, this is as efficient as I could come up with:
For the original question, CHOOSE ONE of the cases...
var number = 1310;
var number = 120;
var number = 10;
var number = 7;
then
// only needs to happen once
var zeroString = "00000";
// one assignment gets the padded number
var paddedNum = zeroString.substring((number + "").length, 4) + bareNum;
//output
alert("The padded number string is: " + paddedNum);
Of course you still need to validate the input. Because this ONLY works reliably under the following conditions:
Number of zeroes in the zeroString is desired_length + 1
Number of digits in your starting number is less than or equal to your desired length
Backstory:
I have a case that needs a fixed length (14 digit) zero-padded number. I wanted to see how basic I could make this. It's run tens of thousands of times on a page load, so efficiency matters. It's not quite re-usable as-is, and it's a bit inelegant. Except that it is very very simple.
For desired n digits padded string, this method requires a string of (at least) n+1 zeroes. Index 0 is the first character in the string, which won't ever be used, so really, it could be anything.
Note also that string.substring() is different from string.substr()!
var bareNum = 42 + '';
var zeroString = "000000000000000";
var paddedNum = zeroString.substring(bareNumber.length, 14) + bareNum
This pulls zeroes from zeroString starting at the position matching the length of the string, and continues to get zeroes to the necessary length of 14. As long as that "14" in the third line is a lower integer than the number of characters in zeroString, it will work.
function pad(n, len) {
return (new Array(len + 1).join('0') + n).slice(-len);
}
might not work in old IE versions.
//to: 0 - to left, 1 - to right
String.prototype.pad = function(_char, len, to) {
if (!this || !_char || this.length >= len) {
return this;
}
to = to || 0;
var ret = this;
var max = (len - this.length)/_char.length + 1;
while (--max) {
ret = (to) ? ret + _char : _char + ret;
}
return ret;
};
Usage:
someString.pad(neededChars, neededLength)
Example:
'332'.pad('0', 6); //'000332'
'332'.pad('0', 6, 1); //'332000'
An approach I like is to add 10^N to the number, where N is the number of zeros you want. Treat the resultant number as a string and slice off the zeroth digit. Of course, you'll want to be careful if your input number might be larger than your pad length, but it's still much faster than the loop method:
// You want to pad four places:
>>> var N = Math.pow(10, 4)
>>> var number = 1310
>>> number < N ? ("" + (N + number)).slice(1) : "" + number
"1310"
>>> var number = 120
>>> number < N ? ("" + (N + number)).slice(1) : "" + number
"0120"
>>> var number = 10
>>> number < N ? ("" + (N + number)).slice(1) : "" + number
"0010"
…
etc. You can make this into a function easily enough:
/**
* Pad a number with leading zeros to "pad" places:
*
* #param number: The number to pad
* #param pad: The maximum number of leading zeros
*/
function padNumber(number, pad) {
var N = Math.pow(10, pad);
return number < N ? ("" + (N + number)).slice(1) : "" + number
}
I wrote a general function for this. It takes an input control and pad length as input.
function padLeft(input, padLength) {
var num = $("#" + input).val();
$("#" + input).val(('0'.repeat(padLength) + num).slice(-padLength));
}
With RegExp/JavaScript:
var number = 7;
number = ('0000'+number).match(/\d{4}$/);
console.log(number);
With Function/RegExp/JavaScript:
var number = 7;
function padFix(n) {
return ('0000'+n).match(/\d{4}$/);
}
console.log(padFix(number));
No loop, no functions
let n = "" + 100;
let x = ("0000000000" + n).substring(n.length);//add your amount of zeros
alert(x + "-" + x.length);
Nate as the best way I found, it's just way too long to read. So I provide you with 3 simples solutions.
1. So here's my simplification of Nate's answer.
//number = 42
"0000".substring(number.toString().length, 4) + number;
2. Here's a solution that make it more reusable by using a function that takes the number and the desired length in parameters.
function pad_with_zeroes(number, len) {
var zeroes = "0".repeat(len);
return zeroes.substring(number.toString().length, len) + number;
}
// Usage: pad_with_zeroes(42,4);
// Returns "0042"
3. Here's a third solution, extending the Number prototype.
Number.prototype.toStringMinLen = function(len) {
var zeroes = "0".repeat(len);
return zeroes.substring(self.toString().length, len) + self;
}
//Usage: tmp=42; tmp.toStringMinLen(4)
Use String.JS librairy function padLeft:
S('123').padLeft(5, '0').s --> 00123
This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 3 years ago.
Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.
NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.
You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the - and read it.
UPDATE: Small one-liner function using the ES2017 String.prototype.padStart method:
const zeroPad = (num, places) => String(num).padStart(places, '0')
console.log(zeroPad(5, 2)); // "05"
console.log(zeroPad(5, 4)); // "0005"
console.log(zeroPad(5, 6)); // "000005"
console.log(zeroPad(1234, 2)); // "1234"
Another ES5 approach:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)
You could extend the Number object:
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
Examples:
(9).pad(); //returns "09"
(7).pad(3); //returns "007"
From https://gist.github.com/1180489
function pad(a, b){
return(1e15 + a + '').slice(-b);
}
With comments:
function pad(
a, // the number to convert
b // number of resulting characters
){
return (
1e15 + a + // combine with large number
"" // convert to string
).slice(-b) // cut leading "1"
}
function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}
Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:
pad.zeros = new Array(5).join('0');
function pad(num, len) {
var str = String(num),
diff = len - str.length;
if(diff <= 0) return str;
if(diff > pad.zeros.length)
pad.zeros = new Array(diff + 1).join('0');
return pad.zeros.substr(0, diff) + str;
}
If the padding count is large and the function is called often enough, it actually outperforms the other methods...