Converting String to Currency Swift
I am having trouble converting my array of String to Currency.
I have created an extension currencyInputFormatting(), however the commas are being placed in the wrong spots.
Here is my code to add the currency to my text.
cell.balanceLabel.text? = (monthlyBalanceStringArray)[indexPath.row].currencyFormatting()
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
var amountWithPrefix = self
let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double))
// number = NSNumber(value: (double / 100))
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
swift currency-formatting
add a comment |
I am having trouble converting my array of String to Currency.
I have created an extension currencyInputFormatting(), however the commas are being placed in the wrong spots.
Here is my code to add the currency to my text.
cell.balanceLabel.text? = (monthlyBalanceStringArray)[indexPath.row].currencyFormatting()
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
var amountWithPrefix = self
let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double))
// number = NSNumber(value: (double / 100))
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
swift currency-formatting
1
"the commas are being placed in the wrong spots." What do you mean? Can you please give an example of inputs, and expected and actual outputs. Also, always post code, data, logs, error message, etc as text (not images) so they are searchable, and can be copied when answering.
– Ashley Mills
Nov 23 '18 at 15:02
add a comment |
I am having trouble converting my array of String to Currency.
I have created an extension currencyInputFormatting(), however the commas are being placed in the wrong spots.
Here is my code to add the currency to my text.
cell.balanceLabel.text? = (monthlyBalanceStringArray)[indexPath.row].currencyFormatting()
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
var amountWithPrefix = self
let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double))
// number = NSNumber(value: (double / 100))
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
swift currency-formatting
I am having trouble converting my array of String to Currency.
I have created an extension currencyInputFormatting(), however the commas are being placed in the wrong spots.
Here is my code to add the currency to my text.
cell.balanceLabel.text? = (monthlyBalanceStringArray)[indexPath.row].currencyFormatting()
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
var amountWithPrefix = self
let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double))
// number = NSNumber(value: (double / 100))
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
swift currency-formatting
swift currency-formatting
edited Nov 24 '18 at 13:23
Rengers
7,75512343
7,75512343
asked Nov 23 '18 at 14:42
user3839056
247
247
1
"the commas are being placed in the wrong spots." What do you mean? Can you please give an example of inputs, and expected and actual outputs. Also, always post code, data, logs, error message, etc as text (not images) so they are searchable, and can be copied when answering.
– Ashley Mills
Nov 23 '18 at 15:02
add a comment |
1
"the commas are being placed in the wrong spots." What do you mean? Can you please give an example of inputs, and expected and actual outputs. Also, always post code, data, logs, error message, etc as text (not images) so they are searchable, and can be copied when answering.
– Ashley Mills
Nov 23 '18 at 15:02
1
1
"the commas are being placed in the wrong spots." What do you mean? Can you please give an example of inputs, and expected and actual outputs. Also, always post code, data, logs, error message, etc as text (not images) so they are searchable, and can be copied when answering.
– Ashley Mills
Nov 23 '18 at 15:02
"the commas are being placed in the wrong spots." What do you mean? Can you please give an example of inputs, and expected and actual outputs. Also, always post code, data, logs, error message, etc as text (not images) so they are searchable, and can be copied when answering.
– Ashley Mills
Nov 23 '18 at 15:02
add a comment |
2 Answers
2
active
oldest
votes
You don't need to replace any any characters using regex. Just use NSNumberFormatter
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
if let value = Double(self) {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
if let str = formatter.string(for: value) {
return str
}
}
return ""
}
}
"74154.7".currencyFormatting() // $74,154.70
"74719.4048014544".currencyFormatting() // $74,719.40
1
you can usestring(for:value)
directly, no need forNSNumber
.
– Sulthan
Nov 23 '18 at 15:25
1
Try "10.k1".currencyFormatting() with this code. It will fail. Wrong answer. The input is an array of string. You can't assume it to be correct.
– Damon
Nov 23 '18 at 15:26
This will create a new NumberFormatter object every time you call this method.
– Leo Dabus
Nov 23 '18 at 16:13
Note that if the goal is to display the currency in US$ you would need also to set a fixed locale to your formatter otherwise 100 dollars might became 100 euros.
– Leo Dabus
Nov 23 '18 at 16:20
works perfectly. thank you so much for the help guys.
– user3839056
Nov 23 '18 at 17:56
add a comment |
Try this
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
var amountWithPrefix = self
let regex = try! NSRegularExpression(pattern: "[^0-9.]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double))
// number = NSNumber(value: (double / 100))
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53448720%2fconverting-string-to-currency-swift%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You don't need to replace any any characters using regex. Just use NSNumberFormatter
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
if let value = Double(self) {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
if let str = formatter.string(for: value) {
return str
}
}
return ""
}
}
"74154.7".currencyFormatting() // $74,154.70
"74719.4048014544".currencyFormatting() // $74,719.40
1
you can usestring(for:value)
directly, no need forNSNumber
.
– Sulthan
Nov 23 '18 at 15:25
1
Try "10.k1".currencyFormatting() with this code. It will fail. Wrong answer. The input is an array of string. You can't assume it to be correct.
– Damon
Nov 23 '18 at 15:26
This will create a new NumberFormatter object every time you call this method.
– Leo Dabus
Nov 23 '18 at 16:13
Note that if the goal is to display the currency in US$ you would need also to set a fixed locale to your formatter otherwise 100 dollars might became 100 euros.
– Leo Dabus
Nov 23 '18 at 16:20
works perfectly. thank you so much for the help guys.
– user3839056
Nov 23 '18 at 17:56
add a comment |
You don't need to replace any any characters using regex. Just use NSNumberFormatter
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
if let value = Double(self) {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
if let str = formatter.string(for: value) {
return str
}
}
return ""
}
}
"74154.7".currencyFormatting() // $74,154.70
"74719.4048014544".currencyFormatting() // $74,719.40
1
you can usestring(for:value)
directly, no need forNSNumber
.
– Sulthan
Nov 23 '18 at 15:25
1
Try "10.k1".currencyFormatting() with this code. It will fail. Wrong answer. The input is an array of string. You can't assume it to be correct.
– Damon
Nov 23 '18 at 15:26
This will create a new NumberFormatter object every time you call this method.
– Leo Dabus
Nov 23 '18 at 16:13
Note that if the goal is to display the currency in US$ you would need also to set a fixed locale to your formatter otherwise 100 dollars might became 100 euros.
– Leo Dabus
Nov 23 '18 at 16:20
works perfectly. thank you so much for the help guys.
– user3839056
Nov 23 '18 at 17:56
add a comment |
You don't need to replace any any characters using regex. Just use NSNumberFormatter
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
if let value = Double(self) {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
if let str = formatter.string(for: value) {
return str
}
}
return ""
}
}
"74154.7".currencyFormatting() // $74,154.70
"74719.4048014544".currencyFormatting() // $74,719.40
You don't need to replace any any characters using regex. Just use NSNumberFormatter
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
if let value = Double(self) {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
if let str = formatter.string(for: value) {
return str
}
}
return ""
}
}
"74154.7".currencyFormatting() // $74,154.70
"74719.4048014544".currencyFormatting() // $74,719.40
edited Nov 23 '18 at 15:29
answered Nov 23 '18 at 15:18
Bilal
9,85952843
9,85952843
1
you can usestring(for:value)
directly, no need forNSNumber
.
– Sulthan
Nov 23 '18 at 15:25
1
Try "10.k1".currencyFormatting() with this code. It will fail. Wrong answer. The input is an array of string. You can't assume it to be correct.
– Damon
Nov 23 '18 at 15:26
This will create a new NumberFormatter object every time you call this method.
– Leo Dabus
Nov 23 '18 at 16:13
Note that if the goal is to display the currency in US$ you would need also to set a fixed locale to your formatter otherwise 100 dollars might became 100 euros.
– Leo Dabus
Nov 23 '18 at 16:20
works perfectly. thank you so much for the help guys.
– user3839056
Nov 23 '18 at 17:56
add a comment |
1
you can usestring(for:value)
directly, no need forNSNumber
.
– Sulthan
Nov 23 '18 at 15:25
1
Try "10.k1".currencyFormatting() with this code. It will fail. Wrong answer. The input is an array of string. You can't assume it to be correct.
– Damon
Nov 23 '18 at 15:26
This will create a new NumberFormatter object every time you call this method.
– Leo Dabus
Nov 23 '18 at 16:13
Note that if the goal is to display the currency in US$ you would need also to set a fixed locale to your formatter otherwise 100 dollars might became 100 euros.
– Leo Dabus
Nov 23 '18 at 16:20
works perfectly. thank you so much for the help guys.
– user3839056
Nov 23 '18 at 17:56
1
1
you can use
string(for:value)
directly, no need for NSNumber
.– Sulthan
Nov 23 '18 at 15:25
you can use
string(for:value)
directly, no need for NSNumber
.– Sulthan
Nov 23 '18 at 15:25
1
1
Try "10.k1".currencyFormatting() with this code. It will fail. Wrong answer. The input is an array of string. You can't assume it to be correct.
– Damon
Nov 23 '18 at 15:26
Try "10.k1".currencyFormatting() with this code. It will fail. Wrong answer. The input is an array of string. You can't assume it to be correct.
– Damon
Nov 23 '18 at 15:26
This will create a new NumberFormatter object every time you call this method.
– Leo Dabus
Nov 23 '18 at 16:13
This will create a new NumberFormatter object every time you call this method.
– Leo Dabus
Nov 23 '18 at 16:13
Note that if the goal is to display the currency in US$ you would need also to set a fixed locale to your formatter otherwise 100 dollars might became 100 euros.
– Leo Dabus
Nov 23 '18 at 16:20
Note that if the goal is to display the currency in US$ you would need also to set a fixed locale to your formatter otherwise 100 dollars might became 100 euros.
– Leo Dabus
Nov 23 '18 at 16:20
works perfectly. thank you so much for the help guys.
– user3839056
Nov 23 '18 at 17:56
works perfectly. thank you so much for the help guys.
– user3839056
Nov 23 '18 at 17:56
add a comment |
Try this
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
var amountWithPrefix = self
let regex = try! NSRegularExpression(pattern: "[^0-9.]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double))
// number = NSNumber(value: (double / 100))
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
}
add a comment |
Try this
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
var amountWithPrefix = self
let regex = try! NSRegularExpression(pattern: "[^0-9.]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double))
// number = NSNumber(value: (double / 100))
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
}
add a comment |
Try this
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
var amountWithPrefix = self
let regex = try! NSRegularExpression(pattern: "[^0-9.]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double))
// number = NSNumber(value: (double / 100))
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
}
Try this
extension String {
// formatting text for currency textField
func currencyFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
var amountWithPrefix = self
let regex = try! NSRegularExpression(pattern: "[^0-9.]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double))
// number = NSNumber(value: (double / 100))
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
}
answered Nov 23 '18 at 14:58
Damon
517317
517317
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53448720%2fconverting-string-to-currency-swift%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
"the commas are being placed in the wrong spots." What do you mean? Can you please give an example of inputs, and expected and actual outputs. Also, always post code, data, logs, error message, etc as text (not images) so they are searchable, and can be copied when answering.
– Ashley Mills
Nov 23 '18 at 15:02