aboutsummaryrefslogtreecommitdiff
path: root/files/id/web/javascript/panduan/numbers_and_dates/index.html
blob: e9681b2adf8ebd2af5642c107b0bf1d0d3b0a185 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
---
title: Numbers and dates
slug: Web/JavaScript/Panduan/Numbers_and_dates
translation_of: Web/JavaScript/Guide/Numbers_and_dates
---
<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}</div>

<p class="summary">Pada Bab ini memperkenalkan cara menggunakan angka dan tanggal pada JavaScript.</p>

<h2 id="Angka">Angka</h2>

<p>Pada JavaScript, semua angka diimplementasikan kedalam <a class="external external-icon" href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format">double-precision 64-bit binary format IEEE 754</a> (mis. angka antara -(2<sup>53</sup> -1) dan 2<sup>53</sup> -1). <strong>Tidak ada jenis spesifik untuk integer</strong>. Selain bisa mewakili angka float, tipe data angka memiliki 3 nilai secara simbolik: <code>+</code>{{jsxref("Infinity")}}, <code>-</code>{{jsxref("Infinity")}}, dan {{jsxref("NaN")}} (bukan sebuah angka). Lihat juga <a href="/en-US/docs/Web/JavaScript/Data_structures">JavaScript tipe data dan struktur</a> untuk konteks dengan tipe data primitif JavaScript yang lain.</p>

<p>Anda dapat menggunakan empat tipe angka literal: desimal, biner, oktal, dan heksadesimal.</p>

<h3 id="Angka_Desimal">Angka Desimal</h3>

<pre class="brush: js">1234567890
42

// Perhatikan ketika menggunakan angka berawalan nol:

0888 // 888 diubah menjadi desimal
0777 // diubah menjadi oktal pada non-strict mode (511 in decimal)
</pre>

<p>Perhatikan bahwa desimal literal dapat dimulai dari nol(0) diikuti angka desimal yang lain, namun jika setiap angka setelah 0 lebih kecil dari 8, angkanya diubah menjadi oktal.</p>

<h3 id="Angka_Biner">Angka Biner</h3>

<p>Sintaks angka biner menggunakan angka nol diikuti dengan huruf kecil atau dengan huruf besar, huruf Latin "B" (<code>0b</code> atau <code>0B</code>). Jika digit setelah <code>0b</code> atau bukan 0 atau 1, menurut <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code> yang dilemparkan: "Missing binary digits after 0b".</p>

<pre class="brush: js">var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607</pre>

<h3 id="Angka_oktal">Angka oktal</h3>

<p>Angka oktal menggunakan awalan angka nol. Jika digit setelah <code>0</code> berada diluar jangkauan 0 hinga 7, angka akan diintrepretasikan sebagai angka desimal.</p>

<pre class="brush: js">var n = 0755; // 493
var m = 0644; // 420
</pre>

<p>Mode ketat pada ECMAScript 5 melarang sintaks oktal. Oktal sintaks bukan bagian dari ECMAScript 5, namun didukung oleh semua peramban dengan cara awalan nomor oktal dengan angka nol: <code>0644 === 420</code> dan <code>"\045" === "%"</code>. Pada ECMAScript 2015, angka oktal didukung jika diawali dengan <code>0o</code>, e.g.: </p>

<pre class="brush: js">var a = 0o10; // ES2015: 8
</pre>

<h3 id="Angka_Heksadesimal">Angka Heksadesimal</h3>

<p>Sintaks heksadesimal menggunakan awalan nol diikuti dengan huruf kecil atau huruf kapital Latin "X" (<code>0x</code> atau <code>0X)</code>. Jika digit setelah 0x berada diluar jangkauan (0123456789ABCDEF),  menurut <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code> yang dilemparkan: "Identifier starts immediately after numeric literal".</p>

<pre class="brush: js">0xFFFFFFFFFFFFFFFFF // 295147905179352830000
0x123456789ABCDEF   // 81985529216486900
0XA                 // 10
</pre>

<h3 id="Eksponensial">Eksponensial</h3>

<pre class="brush: js">1E3   // 1000
2e6   // 2000000
0.1e2 // 10</pre>

<h2 id="Angka_object"><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">Angka</span></font> object</h2>

<p>The built-in {{jsxref("Number")}} objek memiliki properti untuk numerik konstanta, seperti nilai maksimal, bukan-sebuah-angka, dan tak terhingga. Anda tidak dapat mengganti nilai dari properti tersebut dan anda dapat menggunakannya sebagai berikut:</p>

<pre class="brush: js">var biggestNum = Number.MAX_VALUE;
var smallestNum = Number.MIN_VALUE;
var infiniteNum = Number.POSITIVE_INFINITY;
var negInfiniteNum = Number.NEGATIVE_INFINITY;
var notANum = Number.NaN;
</pre>

<p>Anda selalu mengacu pada properti dari objek angka yang telah ditentukan seperti yang ditunjukkan diatas, dan bukan sebagai properti objek angka yang anda tentukan.</p>

<p>Tabel berikut meringkas sifat-sifat nomor object.</p>

<table class="standard-table">
 <caption>Properties of <code>Number</code></caption>
 <thead>
  <tr>
   <th scope="col">Properti</th>
   <th scope="col">Deskripsi</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{jsxref("Number.MAX_VALUE")}}</td>
   <td>Merepresantikan angka maksimal / terbesar</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.MIN_VALUE")}}</td>
   <td>Merepresantikan angka minimal / terkecil</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.NaN")}}</td>
   <td>Nilai spesial "bukan sebuah angka"</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.NEGATIVE_INFINITY")}}</td>
   <td>Nilai spesial negatif tak terhingga; dikembalikan pada overflow</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.POSITIVE_INFINITY")}}</td>
   <td>Nilai spesial positif tak terhingga; dikembalikan pada overflow</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.EPSILON")}}</td>
   <td>Perbedaan antara satu dan nilai terkecil lebih besar dari satu yang dapat direpresentasikan sebagai {{jsxref("Number")}}.</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.MIN_SAFE_INTEGER")}}</td>
   <td>Bilangan bulat aman minimum dalam JavaScript.</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.MAX_SAFE_INTEGER")}}</td>
   <td>Bilangan bulat aman maksimum dalam JavaScript.</td>
  </tr>
 </tbody>
</table>

<table class="standard-table">
 <caption>Methods of <code>Number</code></caption>
 <thead>
  <tr>
   <th>Method</th>
   <th>Description</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{jsxref("Number.parseFloat()")}}</td>
   <td>Parses a string argument and returns a floating point number.<br>
    Same as the global {{jsxref("parseFloat", "parseFloat()")}} function.</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.parseInt()")}}</td>
   <td>Parses a string argument and returns an integer of the specified radix or base.<br>
    Same as the global {{jsxref("parseInt", "parseInt()")}} function.</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.isFinite()")}}</td>
   <td>Determines whether the passed value is a finite number.</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.isInteger()")}}</td>
   <td>Determines whether the passed value is an integer.</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.isNaN()")}}</td>
   <td>Determines whether the passed value is {{jsxref("Global_Objects/NaN", "NaN")}}. More robust version of the original global {{jsxref("Global_Objects/isNaN", "isNaN()")}}.</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.isSafeInteger()")}}</td>
   <td>Determines whether the provided value is a number that is a <dfn>safe integer</dfn>.</td>
  </tr>
 </tbody>
</table>

<p>Prototipe Angka menyediakan metode-metode untuk menampilkan informasi dari objek angka dalam format bervariasi. Tabel berikut meringkas metode-metode prototipe angka.</p>

<table class="standard-table">
 <caption>Methods of <code>Number.prototype</code></caption>
 <thead>
  <tr>
   <th scope="col">Method</th>
   <th scope="col">Description</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{jsxref("Number.toExponential", "toExponential()")}}</td>
   <td>Mengembalikan string yang merepresentasikan nomor dalam notasi eksponensial.</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.toFixed", "toFixed()")}}</td>
   <td>Mengembalikan string yang merepresentasikan nomor dalam notasi fixed-point.</td>
  </tr>
  <tr>
   <td>{{jsxref("Number.toPrecision", "toPrecision()")}}</td>
   <td>Mengembalikan string yang merepresentasikan nomor dalam notasi fixed-point yang lebih spesifik.</td>
  </tr>
 </tbody>
</table>

<h2 id="Math_object"><code>Math</code> object</h2>

<p>The built-in {{jsxref("Math")}} objek memiliki properti dan metode-metode untuk konstanta matematika dan fungsi-fungsi. Sebagai contoh, objek matematik <code>PI</code> properti memiliki nilai (3.141...), yang akan anda gunakan dalam aplikasi sebagai</p>

<pre class="brush: js">Math.PI
</pre>

<p>Demikian pula, fungsi standard matematika merupakan metode-metode <code>Math</code>. termasuk trigonometri, logaritma, eksponensial, dan fungsi lainnya. Sebagai contoh, jika anda ingin menggunakan fungsi trigonometri sin, anda akan menulis</p>

<pre class="brush: js">Math.sin(1.56)
</pre>

<p>Perhatikan bahwa semua metode trigonometri matematika menggunakan argumen dalam radian.</p>

<p>Tabel berikut meringkas metode-metode objek matematik.</p>

<table class="standard-table">
 <caption>Methods of <code>Math</code></caption>
 <thead>
  <tr>
   <th scope="col">Method</th>
   <th scope="col">Description</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{jsxref("Math.abs", "abs()")}}</td>
   <td>Nilai absolut</td>
  </tr>
  <tr>
   <td>{{jsxref("Math.sin", "sin()")}}, {{jsxref("Math.cos", "cos()")}}, {{jsxref("Math.tan", "tan()")}}</td>
   <td>Fungsi trigonometri standar; dengan argumen dalam radian.</td>
  </tr>
  <tr>
   <td>{{jsxref("Math.asin", "asin()")}}, {{jsxref("Math.acos", "acos()")}}, {{jsxref("Math.atan", "atan()")}}, {{jsxref("Math.atan2", "atan2()")}}</td>
   <td>Fungsi trigonometri terbalik; mengembalikan nilai dalam radian.</td>
  </tr>
  <tr>
   <td>{{jsxref("Math.sinh", "sinh()")}}, {{jsxref("Math.cosh", "cosh()")}}, {{jsxref("Math.tanh", "tanh()")}}</td>
   <td>Fungsi hiperbolik. argumen dalam sudut hiperbolik.</td>
  </tr>
  <tr>
   <td>{{jsxref("Math.asinh", "asinh()")}}, {{jsxref("Math.acosh", "acosh()")}}, {{jsxref("Math.atanh", "atanh()")}}</td>
   <td>Fungsi hiperbolik terbalik. mengembalikan nilai dalam sudut hiperbolik.</td>
  </tr>
  <tr>
   <td>
    <p>{{jsxref("Math.pow", "pow()")}}, {{jsxref("Math.exp", "exp()")}}{{jsxref("Math.expm1", "expm1()")}}, {{jsxref("Math.log10", "log10()")}}, {{jsxref("Math.log1p", "log1p()")}}, {{jsxref("Math.log2", "log2()")}}</p>
   </td>
   <td>Fungsi eksponen dan logaritma.</td>
  </tr>
  <tr>
   <td>{{jsxref("Math.floor", "floor()")}}, {{jsxref("Math.ceil", "ceil()")}}</td>
   <td>Mengembalikan angka bulat terkecil/terbesar kurang/lebih dari atau sama dengan pada sebuah argumen.</td>
  </tr>
  <tr>
   <td>{{jsxref("Math.min", "min()")}}, {{jsxref("Math.max", "max()")}}</td>
   <td>Mengembalikan nilai minimum/maksimum sebuah koma terpisah dari angka sebagai argumen.</td>
  </tr>
  <tr>
   <td>{{jsxref("Math.random", "random()")}}</td>
   <td>Megembalikan angka acak antara 0 dan 1.</td>
  </tr>
  <tr>
   <td>{{jsxref("Math.round", "round()")}}, {{jsxref("Math.fround", "fround()")}}, {{jsxref("Math.trunc", "trunc()")}},</td>
   <td>Fungsi pembulatan dan pemotongan.</td>
  </tr>
  <tr>
   <td>{{jsxref("Math.sqrt", "sqrt()")}}, {{jsxref("Math.cbrt", "cbrt()")}}, {{jsxref("Math.hypot", "hypot()")}}</td>
   <td>Akar kuadrat, akar pangkat tiga, akar kuadrat dari jumlah argumen persegi.</td>
  </tr>
  <tr>
   <td>{{jsxref("Math.sign", "sign()")}}</td>
   <td>tanda sebuah angka, mengindikasikan angka apapun merupakan angka positif, negatif, atau nol.</td>
  </tr>
  <tr>
   <td>{{jsxref("Math.clz32", "clz32()")}},<br>
    {{jsxref("Math.imul", "imul()")}}</td>
   <td>Angka yang dimulai dari nol bit dalam 32-bit.<br>
    Hasil dari C-like 32-bit perkalian dari dua argumen.</td>
  </tr>
 </tbody>
</table>

<p>Tidak seperti beberapa objek lainnya, anda tidak perlu membuat objek matematika sendiri. anda selalu menggunakan built-in Math object.</p>

<h2 id="Date_object"><code>Date</code> object</h2>

<p>JavaScript does not have a date data type. However, you can use the {{jsxref("Date")}} object and its methods to work with dates and times in your applications. The <code>Date</code> object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.</p>

<p>JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00, with a Unix Timestamp being the number of seconds since January 1, 1970, 00:00:00.</p>

<p>The <code>Date</code> object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.</p>

<p>To create a <code>Date</code> object:</p>

<pre class="brush: js">var dateObjectName = new Date([parameters]);
</pre>

<p>where <code>dateObjectName</code> is the name of the <code>Date</code> object being created; it can be a new object or a property of an existing object.</p>

<p>Calling <code>Date</code> without the <code>new</code> keyword returns a string representing the current date and time.</p>

<p>The <code>parameters</code> in the preceding syntax can be any of the following:</p>

<ul>
 <li>Nothing: creates today's date and time. For example, <code>today = new Date();</code>.</li>
 <li>A string representing a date in the following form: "Month day, year hours:minutes:seconds." For example, <code>var Xmas95 = new Date("December 25, 1995 13:30:00")</code>. If you omit hours, minutes, or seconds, the value will be set to zero.</li>
 <li>A set of integer values for year, month, and day. For example, <code>var Xmas95 = new Date(1995, 11, 25)</code>.</li>
 <li>A set of integer values for year, month, day, hour, minute, and seconds. For example, <code>var Xmas95 = new Date(1995, 11, 25, 9, 30, 0);</code>.</li>
</ul>

<h3 id="Methods_of_the_Date_object">Methods of the <code>Date</code> object</h3>

<p>The <code>Date</code> object methods for handling dates and times fall into these broad categories:</p>

<ul>
 <li>"set" methods, for setting date and time values in <code>Date</code> objects.</li>
 <li>"get" methods, for getting date and time values from <code>Date</code> objects.</li>
 <li>"to" methods, for returning string values from <code>Date</code> objects.</li>
 <li>parse and UTC methods, for parsing <code>Date</code> strings.</li>
</ul>

<p>With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a <code>getDay</code> method that returns the day of the week, but no corresponding <code>setDay</code> method, because the day of the week is set automatically. These methods use integers to represent these values as follows:</p>

<ul>
 <li>Seconds and minutes: 0 to 59</li>
 <li>Hours: 0 to 23</li>
 <li>Day: 0 (Sunday) to 6 (Saturday)</li>
 <li>Date: 1 to 31 (day of the month)</li>
 <li>Months: 0 (January) to 11 (December)</li>
 <li>Year: years since 1900</li>
</ul>

<p>For example, suppose you define the following date:</p>

<pre class="brush: js">var Xmas95 = new Date('December 25, 1995');
</pre>

<p>Then <code>Xmas95.getMonth()</code> returns 11, and <code>Xmas95.getFullYear()</code> returns 1995.</p>

<p>The <code>getTime</code> and <code>setTime</code> methods are useful for comparing dates. The <code>getTime</code> method returns the number of milliseconds since January 1, 1970, 00:00:00 for a <code>Date</code> object.</p>

<p>For example, the following code displays the number of days left in the current year:</p>

<pre class="brush: js">var today = new Date();
var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month
endYear.setFullYear(today.getFullYear()); // Set year to this year
var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
var daysLeft = Math.round(daysLeft); //returns days left in the year
</pre>

<p>This example creates a <code>Date</code> object named <code>today</code> that contains today's date. It then creates a <code>Date</code> object named <code>endYear</code> and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between <code>today</code> and <code>endYear</code>, using <code>getTime</code> and rounding to a whole number of days.</p>

<p>The <code>parse</code> method is useful for assigning values from date strings to existing <code>Date</code> objects. For example, the following code uses <code>parse</code> and <code>setTime</code> to assign a date value to the <code>IPOdate</code> object:</p>

<pre class="brush: js">var IPOdate = new Date();
IPOdate.setTime(Date.parse('Aug 9, 1995'));
</pre>

<h3 id="Example">Example</h3>

<p>In the following example, the function <code>JSClock()</code> returns the time in the format of a digital clock.</p>

<pre class="brush: js">function JSClock() {
  var time = new Date();
  var hour = time.getHours();
  var minute = time.getMinutes();
  var second = time.getSeconds();
  var temp = '' + ((hour &gt; 12) ? hour - 12 : hour);
  if (hour == 0)
    temp = '12';
  temp += ((minute &lt; 10) ? ':0' : ':') + minute;
  temp += ((second &lt; 10) ? ':0' : ':') + second;
  temp += (hour &gt;= 12) ? ' P.M.' : ' A.M.';
  return temp;
}
</pre>

<p>The <code>JSClock</code> function first creates a new <code>Date</code> object called <code>time</code>; since no arguments are given, time is created with the current date and time. Then calls to the <code>getHours</code>, <code>getMinutes</code>, and <code>getSeconds</code> methods assign the value of the current hour, minute, and second to <code>hour</code>, <code>minute</code>, and <code>second</code>.</p>

<p>The next four statements build a string value based on the time. The first statement creates a variable <code>temp</code>, assigning it a value using a conditional expression; if <code>hour</code> is greater than 12, (<code>hour - 12</code>), otherwise simply hour, unless hour is 0, in which case it becomes 12.</p>

<p>The next statement appends a <code>minute</code> value to <code>temp</code>. If the value of <code>minute</code> is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to <code>temp</code> in the same way.</p>

<p>Finally, a conditional expression appends "P.M." to <code>temp</code> if <code>hour</code> is 12 or greater; otherwise, it appends "A.M." to <code>temp</code>.</p>

<p>{{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}</p>