Write a program to convert the number to currency string format.
Example 1:
Input: 1392431860
Output: 1,392,431,860.00
Approach :
Java
public class CurrencyNumberFormat {public static void main(String[] args) {int amount = 1392431860;System.out.println(currencyFormat(amount));System.out.println(String.format("%,d", amount));}// Method used for convert number to corrency formatpublic static String currencyFormat(int amount) {String ans = "";String x = "";int cnt = 0;// iterate till the amount// becomes 0while (amount > 0) {x = (amount % 10) + x;cnt++;amount = amount / 10;// if count becomes 3if (cnt == 3) {// if amount is not equal to 0// then insert ',' +x+ansif (amount != 0)ans = ',' + x + ans;// else x+anselseans = x + ans;// reset xx = "";// reset countcnt = 0;}}// if thier is something left// then add thisans = x + ans;// retunr the final answerreturn ans;}}
C++
#include <bits/stdc++.h>using namespace std;//function to format the//amount into currency format// eg. 1234 output= 1,234string currencyFormat(long long int amount){string ans="";string x="";long long int cnt=0;//iterate till the amount//becomes 0while(amount>0){x=to_string(amount%10)+x;cnt++;amount=amount/10;//if count becomes 3if(cnt==3){//if amount is not equal to 0//then insert ',' +x+ansif(amount!=0)ans=','+x+ans;//else x+anselseans=x+ans;//reset xx="";//reset countcnt=0;}}//if thier is something left//then add thisans=x+ans;//retunr the final answerreturn ans;}int main(){long long int amount =1392431860;string format_string=currencyFormat(amount);cout<<format_string<<"\n";return 0;}
No comments:
Post a Comment