Convert String to currency format
Given a number N. Convert N into an Indian currency format. For more understanding, please look into examples.
Examples:
Input: N = 1000000
Output: Rs 10, 00, 000Input: N = 1500
Output: Rs 1, 500
Approach: Steps involved in the implementation of code:
- We need to check whether the length of the string is even or odd.
- If the length of the string is less than equal to 3 we will simply return it else we will do the following, newString = “”.
- if the length is odd:
- we will the first character into a new string newSstring = N[0].
- and then we will and commas new string = “, “.
- Now we will skip the two characters and then add “, ” till the length < n-2.
- And at last, we will add the remaining characters to the newString.
Below is the implementation of the code:
C++
// C++ implementation of the code#include <bits/stdc++.h>using namespace std;// Function to convert N// into indian currencystring goodFormat(string s, int n){ // If length if less than 3 if (n <= 3) return "Rs. " + s; string ans = ""; int start = 0, cnt = 0; // If length is even if (n % 2 == 0) { ans += s[0]; ans += ", "; start = 1; } while (start < n - 2) { if (cnt == 2) { ans += ", "; cnt = 0; continue; } else { ans += s[start]; cnt++; } start++; } for (int i = start; i < n; i++) ans += s[i]; return "Rs " + ans;}// Drivers codeint main(){ string s = "1000000"; int l = s.length(); // Function Call cout << goodFormat(s, l); return 0;} |
Java
// Java implementation of the codeimport java.util.*;class GFG { // Function to convert N // into Indian currency static String goodFormat(String s, int n) { // If length is less than 3 if (n <= 3) return "Rs. " + s; String ans = ""; int start = 0, cnt = 0; // If length is even if (n % 2 == 0) { ans += s.charAt(0); ans += ", "; start = 1; } while (start < n - 2) { if (cnt == 2) { ans += ", "; cnt = 0; continue; } else { ans += s.charAt(start); cnt++; } start++; } for (int i = start; i < n; i++) ans += s.charAt(i); return "Rs " + ans; } // Drivers code public static void main(String[] args) { String s = "1000000"; int l = s.length(); // Function Call System.out.println(goodFormat(s, l)); }}// This code is contributed by prasad264 |
Output
Rs 10, 00, 000
Time Complexity: O(N)
Auxiliary Space: O(1)






Please Login to comment...