1
+ import { useState } from 'react' ;
2
+ import { block } from 'million/react' ;
3
+
4
+ interface Results {
5
+ totalInvestment : number ;
6
+ totalPayment : number ;
7
+ totalInterest : number ;
8
+ }
9
+
10
+ const InvestmentCalculator = block ( ( ) => {
11
+ const [ investmentAmount , setInvestmentAmount ] = useState < number | string > ( '' ) ;
12
+ const [ interestRate , setInterestRate ] = useState < number | string > ( '' ) ;
13
+ const [ numberOfYears , setNumberOfYears ] = useState < number | string > ( '' ) ;
14
+ const [ results , setResults ] = useState < Results | null > ( null ) ;
15
+
16
+
17
+ const calculateInterest = ( ) => {
18
+ const p = parseFloat ( investmentAmount as string ) ;
19
+ const r = parseFloat ( interestRate as string ) ;
20
+ const n = parseInt ( numberOfYears as string , 10 ) ;
21
+
22
+ if ( isNaN ( p ) || isNaN ( r ) || isNaN ( n ) || p <= 0 || r <= 0 || n <= 0 ) {
23
+ alert ( 'Please enter valid numbers.' ) ;
24
+ return ;
25
+ }
26
+
27
+ const totalInterest = ( p * r * n ) / 100 ;
28
+ const totalPayment = totalInterest + p ;
29
+ const totalInvestment = p ;
30
+
31
+ setResults ( {
32
+ totalInvestment,
33
+ totalPayment,
34
+ totalInterest,
35
+ } ) ;
36
+ }
37
+
38
+
39
+ return (
40
+ < div className = "InvestmentCalculator" >
41
+ < h1 > Investment Calculator</ h1 >
42
+ < div >
43
+ < label > Total Investment ($): </ label >
44
+ < input
45
+ type = "number"
46
+ value = { investmentAmount }
47
+ onChange = { ( e ) => setInvestmentAmount ( e . target . value ) }
48
+ style = { { display : 'block' , marginBottom : '15px' } }
49
+ />
50
+ </ div >
51
+ < div >
52
+ < label > Interest Rate (Annual %): </ label >
53
+ < input
54
+ type = "number"
55
+ value = { interestRate }
56
+ onChange = { ( e ) => setInterestRate ( e . target . value ) }
57
+ style = { { display : 'block' , marginBottom : '15px' } }
58
+ />
59
+ </ div >
60
+ < div >
61
+ < label > Duration (Years): </ label >
62
+ < input
63
+ type = "number"
64
+ value = { numberOfYears }
65
+ onChange = { ( e ) => setNumberOfYears ( e . target . value ) }
66
+ style = { { display : 'block' , marginBottom : '15px' } }
67
+ />
68
+ </ div >
69
+ < button onClick = { calculateInterest } > Calculate</ button >
70
+
71
+ { results && (
72
+ < div className = "results" >
73
+ < h2 > Results:</ h2 >
74
+ < div > End Balance: ${ results . totalPayment . toFixed ( 2 ) } </ div >
75
+ < div > Total Investment : ${ results . totalInvestment . toFixed ( 2 ) } </ div >
76
+ < div > Total Interest: ${ results . totalInterest . toFixed ( 2 ) } </ div >
77
+ </ div >
78
+ ) }
79
+ </ div >
80
+ ) ;
81
+ } ) ;
82
+
83
+ export default InvestmentCalculator ;
0 commit comments