Converting String to Currency Swift





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-3















I am having trouble converting my array of String to Currency.



enter image description here



enter image description here



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)!

}









share|improve this question




















  • 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




















-3















I am having trouble converting my array of String to Currency.



enter image description here



enter image description here



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)!

}









share|improve this question




















  • 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
















-3












-3








-3








I am having trouble converting my array of String to Currency.



enter image description here



enter image description here



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)!

}









share|improve this question
















I am having trouble converting my array of String to Currency.



enter image description here



enter image description here



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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 13:23









wvteijlingen

8,96312545




8,96312545










asked Nov 23 '18 at 14:42









user3839056user3839056

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
















  • 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














2 Answers
2






active

oldest

votes


















3














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





share|improve this answer





















  • 1





    you can use string(for:value) directly, no need for NSNumber.

    – 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














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)!
}
}





share|improve this answer
























    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
    });


    }
    });














    draft saved

    draft discarded


















    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









    3














    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





    share|improve this answer





















    • 1





      you can use string(for:value) directly, no need for NSNumber.

      – 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
















    3














    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





    share|improve this answer





















    • 1





      you can use string(for:value) directly, no need for NSNumber.

      – 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














    3












    3








    3







    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





    share|improve this answer















    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






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 23 '18 at 15:29

























    answered Nov 23 '18 at 15:18









    BilalBilal

    10.3k52944




    10.3k52944








    • 1





      you can use string(for:value) directly, no need for NSNumber.

      – 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





      you can use string(for:value) directly, no need for NSNumber.

      – 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













    -1














    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)!
    }
    }





    share|improve this answer




























      -1














      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)!
      }
      }





      share|improve this answer


























        -1












        -1








        -1







        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)!
        }
        }





        share|improve this answer













        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)!
        }
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 14:58









        DamonDamon

        5361619




        5361619






























            draft saved

            draft discarded




















































            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.




            draft saved


            draft discarded














            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





















































            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







            Popular posts from this blog

            If I really need a card on my start hand, how many mulligans make sense? [duplicate]

            Alcedinidae

            Can an atomic nucleus contain both particles and antiparticles? [duplicate]