In Dart, how do you set the number of decimals in a double variable? [duplicate] - flutter

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.

Related

Converting a double to a long, then back to double?

Does Converting a double to a long, then back to double, guarantees keeping the exact value to the left of the decimal point?
EDIT:
Working with C++: Conversion is as follows:
double d_var = func();
long l_var = (long)d_var;
d_var = (double)l_var;
For every programming language I have worked with it will keep the value to the left of the decimal point.
For typecast then the fractions are removed when casting, but for range then double can hold bigger numbers than long and therefore becomes something else during a typecast.
At least for common languages I can think of.

Round off a Double to Two Decimal Points [duplicate]

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.

Which method is used in Kotlin's Double.toInt(), rounding or truncation?

On the official API doc, it says:
Returns the value of this number as an Int, which may involve rounding or truncation.
I want truncation, but not sure. Can anyone explain the exact meaning of may involve rounding or truncation?
p.s.: In my unit test, (1.7).toInt() was 1, which might involve truncation.
The KDoc of Double.toInt() is simply inherited from Number.toInt(), and for that, the exact meaning is, it is defined in the concrete Number implementation how it is converted to Int.
In Kotlin, the Double operations follow the IEEE 754 standard, and the semantics of the Double.toInt() conversion is the same as that of casting double to int in Java, i.e. normal numbers are rounded toward zero, dropping the fractional part:
println(1.1.toInt()) // 1
println(1.7.toInt()) // 1
println(-2.3.toInt()) // -2
println(-2.9.toInt()) // -2
First of all, this documentation is straight up copied from Java's documentation.
As far as I know it only truncates the decimal points, e.g. 3.14 will become 3, 12.345 will become 12, and 9.999 will become 9.
Reading this answer and the comments under it suggests that there is no actual rounding. The "rounding" is actually truncating. The rounding differs from Math.floor that instead of rounding to Integer.MIN_VALUE it rounds to 0.
use this roundToInt() in kotlin
import kotlin.math.roundToInt
fun main() {
var r = 3.1416
var c:Int = r.roundToInt()
println(c)
}
Use the function to.Int(), and send the value to the new variable which is marked as Int:
val x: Int = variable_name.toInt()

How to round up a number if it's not an integer?

I want to calculate a simple number, and if the number is not an integer I want to round it up.
For instance, if after a calculation I get 1.2, I want to change it to 2. If the number is 3.7, I want to change it to 4 and so on.
You can use math.ceil to round a Double up and toInt to convert the Double to an Int.
def roundUp(d: Double) = math.ceil(d).toInt
roundUp(1.2) // Int = 2
roundUp(3.7) // Int = 4
roundUp(5) // Int = 5
The ceil function is also directly accessible on the Double:
3.7.ceil.toInt // 4
Having first imported math
import scala.math._ (the final dot & underscore are crucial for what comes next)
you can simply write
ceil(1.2)
floor(3.7)
plus a bunch of other useful math functions like
exp(1)
pow(2,2)
sqrt(pow(2,2)

How to make a simple division of Double by Int in Swift?

Looking at various posts on this topic but still no luck. Is there a simple way to make division/conversion when dividing Double (or Float) with Int? Here is a simple example in playground returning and error "Double is not convertible to UInt8".
var score:Double = 3.00
var length:Int = 2 // it is taken from some an array lenght and does not return decimal or float
var result:Double = (score / length )
Cast the int to double with var result:Double=(score/Double(length))
What this will do is before computing the division it will create a new Double variable with int inside parentheses hence constructor like syntax.
You cannot combine or use different variable types together.
You need to convert them all to the same type, to be able to divide them together.
The easiest way I see to make that happen, would be to make the Int a Double.
You can do that quite simply do that by adding a ".0" on the end of the Integer you want to convert.
Also, FYI:
Floats are pretty rarely used, so unless you're using them for something specific, its also just more fluid to use more common variables.