Converting integer so it has two decimal places in Swift - ios

I have a variable called 'totalMonthly like follows:
var totalMonthly: Float = 0.00
I then have a function which gets called on viewDidLoad which pulls an array of values from an API request, and loops through them, adding them on to the totalMonthly variable.
This function also contains a Dispatch so that I can render the variable on my screen upon page load inside of a monthlyLabel text label.
func calculateMonthly() {
for account in accounts {
totalMonthly += Float(account.repaymentTotal)!
print(account.repaymentTotal)
}
DispatchQueue.main.async {
print(self.totalMonthly)
self.monthlyLabel.text = "£\(self.totalMonthly)"
}
}
However, the values are always showing with just one decimal place - for example it might be 690.0, or 720.2.
I want them instead to display as 690.00, or 720.20.
I have tried converting it into a %.2f format as a string, but that just automatically makes the variable change to 0.00 and render that on the screen.
For reference, the values pulled from the API are stored as flat values (230, 540 etc), so I figured I'd need to convert them into floats, but no luck.
Can anyone point out what I'm doing wrong here?

Related

Odd Shortened Syntax for Closures in Swift?

I'm trying to fully wrap my head around closures in Swift. I think I understand the basics. However, I ran into some odd syntax and would appreciate if someone can understand what it means.
I'm going to show the shortened syntax that I came across, but first I'll show how I would write this code without the shortned syntax. I think I understand everything that's going on in the following code, but I'll narrate it just to make sure :)
//function
func manipulate(numbers: [Int], using algorithm: (Int) -> Int){
for number in numbers{
let result = algorithm(number)
print("Manipulating \(number) produced \(result)")
}
}
//trailing closure syntax
manipulate(numbers: [1,2,3]){(number: Int) -> Int in
return number * number
}
Okay, so we're basically declaring a function called manipulate that takes 2 parameters. One of these parameters is numbers and it is an array of Ints. The second parameter, known as using externally and algorithm internally is a closure, which takes an Int as a parameter, and returns an Int.
Okay cool, the function then goes through all the numbers in the array numbers and applies the result of calling the closure, algorithm on each number.
Okay, so that's what the function does, now, let's call it with trailing closure syntax.
What I did was call the function, manipulate and pass in the first parameter, numbers, and then, going by the trailing closure syntax, defined the closure that I'm going to be using. It's taking a parameter, which I called number, that is an Int, and it's returning another Int, number * number.
This code makes perfect sense to me.
Here's the variant that tripped me up. The definition of the function was exactly the same, but, the function was called in a way that I don't understand.
//function
func manipulate(numbers: [Int], using algorithm: (Int) -> Int){
for number in numbers{
let result = algorithm(number)
print("Manipulating \(number) produced \(result)")
}
}
//trailing closure syntax
manipulate(numbers: [1,2,3]){ number in
number * number
}
First of all, we're not specifying the type of the parameter that the closure takes, and we're also not specifying the type of the return value. Also, what does number even mean in this context when we're calling the function?
I'd appreciate it if someone could explain what's going on here. I'm pretty sure it's some idiomatic syntax in Swift, but I don't quite understand it.
Thanks!

Int Variable won't let me add data from UI text field

I'm currently working on making a savings app in Xcode 10. I'm working on a feature that lets users add the amount of money they have saved for something into the app through a UI text field. I can't find a way to return the text from the text field to an Integer and add that to the total sum of money that has been saved. Also whenever I tried to add a test variable I got plenty of errors.
var amountSavedSoFar += amountOfMoneySaved
Both I have set to be integers. I'm trying to set amountOfMoneySaved equal to the numbers in the text field, but it doesn't seem to work.
'+=' is not a prefix unary operator
Consecutive statements on a line must be separated by ';'
Type annotation missing in pattern
Unary operator cannot be separated from its operand
You've got a few issues as you mentioned:
amountSavedSoFar is declared in the saveAmount function and will not be persisted if you call that function more than once.
amountSaved.text is not being converted from String to the appropriate type (Int, Double, etc.)
amountSavedSoFar isn't typed or initialized.
Try something like:
var amountSavedSoFar: Int = 0
#IBAction func saveAmount(_ sender: Any) {
//Convert the text and default to zero if conversion fails
amountSavedSoFar += Int(amountSaved.text) ?? 0
}

How do I round a decimal result up in Thymeleaf (same behavior as Math.ceil)?

I am doing table pagination logic for my project using Thymeleaf.
I have two values:
int totalRows
int rowsPerPage
The operation I want to do is something along the lines of Math.ceil((1.0 + totalRows) / rowsPerPage) to store in a variable that represents the total number of pages necessary.
However, I'm not sure how to do that ceil() operation to convert it from a decimal to an integer.
If you are working with Spring then you can add a bean that has the method you want Math.ceil. Then call this method in the template. Something like
#Component
public class ThymeMath {
public int ceil(int a, int b) {
return Math.ceil....
}
}
Then in the template
${#thymeMath.ceil(a, b)}
That is in the case you really need to do it in Thymeleaf. In the more general case you can calculate the variable in the Java code and add it to the model.
You can just call Math.ceil with thymeleaf, use:
${T(Math).ceil(yourNumber)}
Since Math.ceil returns a double type, you can also encapsulate that in the following expression to remove the trailing ".0" if you wish (the last "1" is the min number of integer digits):
${#numbers.formatInteger(T(Math).ceil(yourNumber),1)}

Generating a random number under super.ViewDidLoad

I am making a 'Guess The Number' Game for a project at school, I want my application to generate one random number between 1-10 and then let me use it under my button which allows the user to guess the number by entering their guess into a text field. I have managed to do some of this, my random number generator is currently under my 'Guess' Button which means every time they press the button the number will change. My solution is to generate a number under super.viewDidLoad and then use it under the button to do the rest, but I'm not sure how to do this.
If I've understood you correctly you want the number to be generated only once instead of on every press.
So you might want something like this:
var randomNumber: Int
override func viewDidLoad() {
super.viewDidLoad()
//Initialization
generateRandomNumber()
}
func generateRandomNumber() {
randomNumber = Int(arc4random_uniform(9)) + 1
}
randomNumber is an instance-variable, so you can access it in all of your methods, for example to check if the user guessed correctly.
Use the standard library functions for high quality random numbers: arc4random() or arc4random_uniform(), just as in Objective-C.
They are in the Darwin module, so you will need to import Darwin if you haven't imported AppKit, UIKit, or Foundation.

HighCharts legend.value and legend.percent items to 2 decimal points Math.Round()

unfortunately with how lengthy this thing is I don't have a fiddle for it, as I didn't build it, but basically all I am trying to do is assure that these values get set to two decimal points, regardless of the value of it. If it's 100, I want it to read 100.00 and that is seemingly the issue I am having. The code for this section, which replaces a template value is this;
if (isLegend) {
if (legendFooterTemplate) {
legendFooterData = legendFooterTemplate.replace("highcharts.value", addCommasToLargeNumber(Math.round(totalValues * 100) / 100));
legendFooterData = legendFooterData.replace("highcharts.percent", Math.round(totalPercent));
legendTable.append("<tr>" + legendFooterData + "</tr>");
}
//make the legend visible
legendTable.css("visibility", "visible");
}
you can see it adds commas to larger numbers and takes that formatted number and plugs it into the template where highcharts.value and highcharts.percent live. I just want to know how I can manipulate the math.round() functions to make it have two decimal points no matter what.
Thank you for any and all help,
Nick G
For percentage use:
this.percentage.toFixed(2)
Example: http://jsfiddle.net/jugal/dTMWP/
For other:
Highcharts.numberFormat(this.y,0)
Example: http://jsfiddle.net/CAKQH/24227/

Resources