This question already has answers here:
Swift double to string
(16 answers)
Closed 5 years ago.
I've written a simple swift program to show how much it costs to run electrical devices. The program works fine (all be it a little clunky - I'm new to swift!) but the result shows several figures after the decimal point so I've attempted to round it off to two decimal places. I'm not having much luck! My code is:
var pricePerkWh: Double = 13.426
var watts: Double = 5.0
var hours: Double = 730.0
var KW: Double = watts/1000
var kWh: Double = KW*hours
var penceMonth: Double = kWh*pricePerkWh
var poundMonth:Double = penceMonth/100
var cost = poundMonth.roundTo(places: 2)
print ("It will cost £\(cost) per month")
From what I've read here, roundTo(places: 2) is used but this resulted in the error
error: Power Costs.playground:6:12: error: value of type 'Double' has no member 'roundTo'
var cost = poundMonth.roundTo(places: 2)
Any pointers would be greatly appreciated!
Thanks
Double indeed has no method roundTo(places:). That‘s a method you would first have to implement yourself.
To do that, see this answer, for example.
Or, if you don’t want to create a separate method, you could directly do this (inspired by the aforementioned answer):
let cost = (poundMonth * 100).rounded() / 100
BUT:
If you don‘t need the rounded value for any further calculations, but want to display it to the user, NumberFormatter is the way to go. For example, it also offers localization. See this answer.
Related
This question already has answers here:
How do you round a double in Dart to a given degree of precision AFTER the decimal point?
(28 answers)
Closed last year.
I want to set a double, let's call it Price, in Dart, so that it always gives me a double of 2 decimal places.
So 2.5 would return 2.50 and 2.50138263 would also return 2.50.
The simplest answer would be double's built-in toStringAsFixed.
In your case
double x = 2.5;
print('${x.toStringAsFixed(2)}');
x = 2.50138263;
print('${x.toStringAsFixed(2)}');
Would both return 2.50. Be aware that this truncates (e.g., 2.519 returns 2.51). It does not use the standard rounding (half-even) banker's algorithm.
I recommend using a NumberFormat from the intl package; The parsing and formatting rules are worth learning since they appear in other languages like Java.
double d = 2.519;
String s = NumberFormat.currency().format(d);
print(s);
returns USD2.52
s = NumberFormat('#.00').format(d);
returns 2.52
Since your are dealing with money, you should probably use NumberFormat.currency, which would add the currency symbol for the current locale.
Your question is more about how Dart handles the type double. Something like the following might work depending on your use-case:
void main() {
double num = 2.50138263;
num = double.parse(num.toStringAsFixed(2));
print(num);
}
More info about how Dart handles double can be found here.
I'm struggling with making sense of how to return the changeDue for my assignment. Trying to revise my incorrect code for class in prep for intro to programming final.
all I am trying to do is: create a method called quarters(). When I pass any double value (ChangeDue) into the method, I want to know precisely how many quarters there are as well as the partial quarter change returned.
Original code:
func getChange(Quarters: Double) -> Double {
var Change = Quarters
return Change;
}
var Quarters = 0.72;
var ChangeDue = getChange(Quarters / .25);
print(ChangeDue)
Slightly revised code which I seem to have made worse:
class changeDue {
var = quarters(.72)
func changeDue(Quarters: Double) {
var Change = Quarters
changeDue = changeDue - (quarters*.25)
}
var ChangeDue = getChange(int / .25);
print(changeDue)
}
notes/Feedback:
create a method called quarters(). When I pass any double value (ChangeDue) into the method, I want to know precisely how many quarters there are as well as the partial quarter change returned.
Create a class level variable, changeDue. This is where you will set your test input e.g. .78, 2.15.
In your method, calculate the number of quarters as the integer of changeDue/.25
Print the number of quarters.
Now you need the revised change after quarters are removed. changeDue=changeDue - (quarters*.25)
quarters = the integer of changedue/.25
changeDue is now = to the previous changeDue - (quarters times .25)
quarters(.72)
the integer of .72/.25 = 2
changedue=.72-(2 x .25) or .72 - .50 =.12
Print changeDue.
Any help would be appreciated. I've been working on this for longer than I want to admit.
Hint 1: Do not work with Double or fractional amounts. Turn dollars into pennies by multiplying everything by 100 before you start. Now you can do everything with integer arithmetic. After you get the answer, you can always divide by 100 to turn it back into dollars, if desired.
Hint 2: Do you know about the % operator? It tells you the remainder after a division.
I don't want to write your code for you (it's you who are being tested, not me, after all), but I'll just demonstrate with a different example:
51 / 7 is 7, because integer division throws away the remainder.
Sure, 7x7 is 49, with something left over. But what?
Answer: 51 % 7 is 2. Do you see?
This question already has answers here:
In Swift 3, how to calculate the factorial when the result becomes too high?
(2 answers)
BigInteger equivalent in Swift?
(6 answers)
Closed 3 years ago.
I am solving a question from HackerRank which asks to print the value of extra-long factorials that can't be stored even in a 64-bit long variable.
I am using NSDecimalNumber to store the value. However, even in this case, the final result is rounded off.
func extraLongFactorials(n: Int) -> Void
{
var factorial: NSDecimalNumber = 1
for index in 1...n
{
let indexInNSDecimal = NSDecimalNumber(value: index)
factorial = factorial.multiplying(by: indexInNSDecimal)
}
let factorialWithoutRounding = factorial.description(withLocale: nil)
print(factorialWithoutRounding)
}
print(extraLongFactorials(n: 45)) // 119622220865480194561963161495657715064000000000000000000
However, the result should be 119622220865480194561963161495657715064383733760000000000.
This link talks about using description(withLocale:).
NSDecimalNumber round long numbers
However, it does not clearly explain how to use the description(withLocale:) method.
I also went through the apple doc https://developer.apple.com/documentation/foundation/nsdecimalnumber/1412789-description. But it also does not explain clearly how to use it.
Can someone please discuss this method in detail.
This question already has answers here:
swift: issue in converting string to double
(2 answers)
Closed 3 years ago.
I have mobile bank app.
When user type amount, then convert string to double i have problem
user typed amount example "8.7" is 8.699999999999999 and when i send request it sending 8.699999999999999
what can i do, to fix it?
I have tried this post:
swift: issue in converting string to double
var amount = "8.7"
var amountDouble = Double(amount)!
var amount = "8.7" . //"8.7"
var amountDouble = Double(amount)! //8.699999999999999
This imprecision is exactly why Double isn't an appropriate datatype for financial domains. Use Decimal instead, which is have perfect precision within its legal range.
This question already has answers here:
Multiplying variables and doubles in swift
(2 answers)
So if string is not NilLiteralConvertible... what do some string functions return?
(1 answer)
Closed 7 years ago.
Hello brand new to Swift, and programming in general. Going through an exercise the code given is exactly:
//: Playground - noun: a place where people can play
import UIKit
let height = 12
let width = 10
let area = height * width
let areaInMeters = area / 10.762
But I get the error, "binary operator / cannot be applied to operands of type Int and Double".
After some digging around I found you can't operate on both an Integer and a Double. So I changed the last line to:
let areaInMeters = (Double)area / 10.762
Then I get the error, "Consecutive statements on a line must be separated by a ;" and it wants me to put the ; after area. None of this is making any sense to me.
Using El Capitan beta and Xcode 7 beta.
height and width will both be inferred as of type Int. Therefore area is also of type Int whilst 10.762 is a Double.
And in Swift safety is paramount so you'll need to have both operands of same type.
Solution is (as Eric D. suggested) is to convert area to a Double:
let areaInMeters = Double(area) / 10.762
Try instead adding a decimal point and a zero to the end of your height and width.
Like so:
let height = 12.0
let width = 10.0
And you won't have to worry about having to deal with an Integer.
Hope this helps. Happy Coding!