How do i assign double value to a string ?
Example :
double a = 5.5,b= 6.0;
double sum = a + b ;
Lable1.Text = sum.ToString();
Result :
11.5
but in label i am getting only 11...how do i display 11.5 in lable ?
Label1.Text = sum.ToString("#0.0");
Generally speaking, "0" is a zero placeholder and "#" is a digit placeholder. You can find more info here. You can also try
Label1.Text = sum.ToString("F1");
where 1 stands for one digit after the decimal point.
Related
Objective-C code:
NSString *str = #"hi";
NSString *strDigit = #"1934"; (or #"193" may be a 3 digit or 4 digit value)
[dayText appendFormat:#"%#%4s,str,[strDigit UTF8String]];
The Objective-C code handles the output string with current alignment when it appears with 3 or 4 digits as output. It is correctly aligning to left and doesn't matter how much digits it is. Any one know how to handle this in Swift?
In Swift I tried with below code and the string is not adjusting the alignment according to the number of digits.
textForTrip += "\(str) \(String(format:"%4s", (strDigit.utf8))"
The %s format expects a pointer to a (NULL-terminated) C string
as argument, that can be obtained with the withCString method.
This would produce the same output as your Objective-C code:
let str = "Hi"
let strDigit = "193"
let text = strDigit.withCString {
String(format: "%#%4s", str, $0)
}
print(text)
It becomes easier if you store the number as integer instead of a
string:
let str = "Hi"
let number = 934
let text = String(format: "%#%4d", str, number)
print(text)
Try this below approach, that might help you
let strDigit = "\("1934".utf8)" //(or #"193" may be a 3 digit or 4 digit value)
var dayText = "Hello, good morning."
dayText += "\(strDigit.prefix(3))"
For my math question app I have two random numbers generated then I have 4 buttons as answers. I want to check the answer if the user pushes the right button but it seems not to work.
num1 and num2 are the labels which the random numbers are generated in so technically
num1.text = "(randomnum1)"
and num2.text = "(randomnum2)" Thanks.
I have the following code under button1 IBaction
var sum = (num1) + (num2)
if btn1.titleLabel = (sum){
check.text = "right"
}
Maybe you should do some convert before you add num1 and num2. (convert strings to integers before adding them up, also, you should convert string to integer fisrt when comparing sum and btn.titleLabel)
you have two options:
if btn1.titleLabel.toInt()! == sum
or
if btn1.titleLabel == String(sum)
consider the difference between = (assign) and == (is equal)
to assign a number to a label use
num1.text = "\(randomnum1)"
I recommend to use backing Int variables like randomnum1 to hold the random numbers which can used for the math for example
var randomnum1 = 0, randomnum2 = 0 // instance variables of the class
randomnum1 = randomFuntion()
randomnum2 = randomFuntion()
num1.text = String(randomnum1)
num2.text = String(randomnum2)
now the labels contain the string values of the random numbers, but you can do the math with the associated variables.
var sum = randomnum1 + randomnum2
after that you can check the result as mentioned above
if btn1.titleLabel == String(sum) {
check.text = "right"
}
An issue here to me that if i use parse string for the result of calculator program for instance,
4.5 * 5.0 = 22.5
how can I use splitting here to depart decimal part from result?
Assuming you're working with strings only :
var str = "4.5 * 5.0 = 22.5 "
// Trim your string in order to remove whitespaces at start and end if there is any.
var trimmedStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Split the string by " " (whitespace)
var splitStr = trimmedStr.componentsSeparatedByString(" ")
// If the split was successful, retrieve the last past (your number result)
var lastPart = ""
if let result = splitStr.last {
lastPart = result
}
// Since it's a XX.X number, split it again by "." (point)
var splitLastPart = lastPart.componentsSeparatedByString(".")
// If the split was successful, retrieve the last past (your number decimal part)
var decimal = ""
if let result = splitLastPart.last {
decimal = result
}
Use modf to extract decimal part from result.
Objective-C :
double integral = 22.5;
double fractional = modf(integral, &integral);
NSLog(#"%f",fractional);
Swift :
var integral:Double = 22.5;
let fractional:Double = modf(integral,&integral);
println(fractional);
Want only interger part from double of float
Want only integer value from double then
let integerValue:Int = Int(integral)
println(integerValue)
Want only integer value from float then
let integerValue:Float = Float(integral)
println(integerValue)
I have used arc4random_uniform() to get the random values from given String or Int. Now I want to join those to values.
var randomNumber = arc4random_uniform(9999) + 1000 // returns random number between 1000 and 9999 e.g. - 7501
let alphabet_array = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
let randomIndex = Int(arc4random_uniform(UInt32(alphabet_array.count)))
let random_alphabet = alphabet_array[randomIndex] // returns random alphabet e.g. - E
What I want is to display 7501 and E together like 7501E
var str="\(randomNumber)\(random_alphabet)" // error
I am getting below error :
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254
Please help how can I display this together.
It works fine with the right punctuation:
var randomNumber = arc4random_uniform(999) + 1000
// returns random number between 1000 and 9999 e.g. - 7501 NOTE 999 not 9999
let alphabet_array = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
// Note missing "=" in OP
let randomIndex = Int(arc4random_uniform(UInt32(alphabet_array.count)))
let random_alphabet = alphabet_array[randomIndex] // returns random alphabet e.g. - E
var str = "\(randomNumber)\(random_alphabet)" // e.g. 1197A
Instead of using string interpolation, you could also convert the random number to a string and just add them together:
let str = randomNumber.description + random_alphabet
I have a function in Android wherein it gets the value returned by a TextView which are
totalcost_venue, totalcost_apparel, totalcost_souvenir, and totalcost_caterer.
The value is converted to double and after which I have to add those values. But I encountered an error when a particular TextView does not return any value. Any help will do. Thanks!
double totalcost_venue_finalconverted = Double.parseDouble(totalcost_venue.getText().toString());
double totalcost_apparel_finalconverted = Double.parseDouble(totalcost_apparel.getText().toString());
double totalcost_caterer_finalconverted = Double.parseDouble(totalcost_caterer.getText().toString());
double totalcost_souvenir_finalconverted = Double.parseDouble(totalcost_souvenir.getText().toString());
double total = (totalcost_venue_finalconverted + totalcost_apparel_finalconverted + totalcost_caterer_finalconverted +totalcost_souvenir_finalconverted);
String total_all= Double.toString(total);
totalcost_all.setText(total_all);
String totalcost_final = totalcost_all.getText().toString();
double budget_converted = Double.parseDouble(budget_event);
double totalcost_converted = Double.parseDouble(totalcost_final);
if(budget_converted <= totalcost_converted){
registerErrorMsg.setText(" Oops!! Already exceeded");
Double.parseDouble() may be throwing an exception if it recieves a null value, or it is recieves text.
To solve your issue with a null value, you could add the following check:
double totalcost_venue_finalconverted = 0;
if(!totalcost_venue.getText().toString().equals("")){
totalcost_venue_finalconverted = Double.parseDouble(totalcost_venue.getText().toString());
}