dart Format 0.052 to 0.06 - dart

How dart implements java with help
BigDecimal b7= b6.multiply(new BigDecimal("0.01")).setScale(2,BigDecimal.ROUND_UP);
Format 0.052 to 0.06

How about using the decimal dart package:
import 'package:decimal/decimal.dart';
import 'dart:math';
Decimal setScale(Decimal decimal, int scale, Decimal roundMethod(Decimal decimal)) {
Decimal scaleVal = Decimal.fromInt(pow(10, scale));
return roundMethod(decimal * scaleVal) / scaleVal;
}
Decimal setScaleRoundDown(Decimal decimal, int scale) => setScale(decimal, scale, (val) => val.floor());
Decimal setScaleRoundUp(Decimal decimal, int scale) => setScale(decimal, scale, (val) => val.ceil());
Decimal setScaleRound(Decimal decimal, int scale) => setScale(decimal, scale, (val) => val.round());
void main() {
print(setScaleRound(Decimal.parse('0.052'), 2)); // 0.05
print(setScaleRoundUp(Decimal.parse('0.052'), 2)); // 0.06
print(setScaleRoundDown(Decimal.parse('0.052'), 2)); // 0.05
}

Related

int and double equality with const in Dart

If I do
final x = (2 == 2.0);
Then x is true.
But if I do
const x = (2 == 2.0);
Then x is false.
I would expect both to be true based on the docs:
If one operand is a double and the other is an int, they are equal if the double has an integer value (finite with no fractional part) and identical(doubleValue.toInt(), intValue) is true.
What's going on here?

Multiply a float and a vector? So val scale : float -> float*float -> float*float?

How do I make a function scale(), that multiplies a float and a vector. It has to use this library shown here? I think it's called library, sorry if that is wrong.
/// Multiplication of a float and a vector
val scale : float -> float * float -> float * float
Spent 4 hours trying to figure it out.
My assignment (Data sciences 3rd week) is, I have a signature-file containing a 2D vector library and I need to make functions out of it using that library.
/// A 2D vector library
/// Vectors are represented as pairs of floats module vec2d
/// The length of a vector
val len : float * float -> float
/// The angle of a vector
val ang : float * float -> float
/// Multiplication of a float and a vector
val scale : float -> float * float -> float * float
/// Addition of two vectors
val add : float * float -> float * float -> float * float
/// Dot product of two vectors
val dot : float * float -> float * float -> float
Currently I have:
// LENGTH OF A VECTOR
// val len : float * float -> float
let len (x: float, y: float) =
sqrt(x**2.0 + y**2.0)
// ANGLE OF A VECTOR
// val ang : float * float -> float
let ang (x: float, y: float) =
Math.Atan2(y, x)
// MULTIPLICATION OF A FLOAT AND A VECTOR
// val scale : float -> float * float -> float * float
let scale () =
None
/// ADDITION OF TWO VECTORS
// add : float * float -> float * float -> float * float
let add (xy1: float, xy2: float) =
None
/// DOT PRODUCT OF TWO VECTORS
// dot : float * float -> float * float -> float
let dot (xy1: float, xy2: float) =
None
Any kind of help/hint would be really helpful! I'm stuck!
Is this what you're looking for?
let scale n (x: float, y: float) =
n*x, n*y
This multiplies each of the values in the vector tuple (x,y) with the float n.

How to convert a double to an int in Dart?

The following produces the below error:
int calc_ranks(ranks)
{
double multiplier = .5;
return multiplier * ranks;
}
The return type double is not a int, as defined by the method calc_ranks. How do I round/cast to an int?
Round it using the round() method:
int calc_ranks(ranks) {
double multiplier = .5;
return (multiplier * ranks).round();
}
You can use any of the following.
double d = 20.5;
int i = d.toInt(); // i = 20
int i = d.round(); // i = 21
int i = d.ceil(); // i = 21
int i = d.floor(); // i = 20
You can simply use toInt() to convert a num to an int.
int calc_ranks(ranks)
{
double multiplier = .5;
return (multiplier * ranks).toInt();
}
Note that to do exactly the same thing you can use the Truncating division operator :
int calc_ranks(ranks) => ranks ~/ 2;
I see a lot of answers, but with less description. Hope my answer will add some value.
Lets initalize the variable, and see how it will change with different methods.
double x = 8.5;
toInt()
It truncates the decimal value.
int a = x.toInt();
print(a); // 8
truncate()
It also truncates the decimal value.
int b = x.truncate();
print(b); // 8
round()
It returns the closest integer. It uses half up rounding mode.
int c = x.round();
print(c); // 9
ceil()
It returns the closest integer greater than the value.
int c = x.ceil();
print(c); // 9
floor()
It returns the closest integer smaller than the value.
int c = x.floor();
print(c); // 8
I looked at the answers above and added some more answers to make it a little easier to understand.
double value = 10.5;
Using toInt()
void main(){
double value = 10.5;
var y = value.toInt();
print(y);
print(y.runtimeType);
}
Using round()
The round() method returns the closest integer to the double.
void main(){
double value = 9.6;
var b = value.round();
print(b);
print(b.runtimeType);
}
Using ceil()
The ceil() method returns the smallest integer that is equal or greater than the given double.
void main(){
double value = 9.5;
var d = value.ceil();
print(d);
print(d.runtimeType);
}
Using floor()
The floor() method returns the greatest integer not greater than the given double.
void main(){
double value = 10.9;
var j = value.floor();
print(j);
print(j.runtimeType);
}
Conclusion
We’ve gone through 4 different techniques to convert a double to an integer in Dart and Flutter. You can choose from the method that fits your use case to solve your problem. Flutter is awesome and provides a lot of amazing features.
To convert double to int just this:
division
double01 ~/ double02
PS: The operator x ~/ y is more efficient than (x / y).toInt().
Multiplication, addition and subtraction
(double01 * double02).toInt
(double01 + double02).toInt
(double01 - double02).toInt
Its easy,
(20.8).round()
For String,
double.tryParse(20.8).round()
from string to int ->
if you string in int format like '10'
then use ---->
int.parse(value)
but if string in double format like '10.6'
then use like this ---->
double.parse(value).toInt()
convert double to int
doubleValue.toInt()
Try this!
int calc_ranks(ranks)
{
double multiplier = .5;
return (multiplier * ranks).truncate();
}
class CurrencyUtils{
static int doubletoint(double doublee) {
double multiplier = .5;
return (multiplier * doublee).round();
}
}
----------------------
CustomText( CurrencyUtils.doubletoint(
double.parse(projPageListss[0].budget.toString())
).toString(),
fontSize: 20,
color: Colors.white,
font: Font.QuicksandSemiBold,
),
There's another alternative, you can first cast the double to 'num' datatype and then convert to int using toInt().
double multiplier = .5;
return ((multiplier * ranks) as num).toInt();
The num type is an inherited data type of the int and double types.
You can cast both int and double to num, then cast it again to whatever you want
(double -> use toDouble(), int -> use toInt())

HSV / RGB color space conversion

I found this code in this forum but Im having doubts with the code.
in this code snippet "int hi = Convert.ToInt32(Math.Floor(hue / 60)) % 6;" why the complete answer is modulus by 6? (%6)
why is " value = value * 255 " value is multiplied by 255?
im reffering to this research paper (p-15 , p-16) and same algorithmic is discussed but I found these differences.
http://www.poynton.com/PDFs/coloureq.pdf
public static Color ColorFromHSV(double hue, double saturation, double value)
{
int hi = Convert.ToInt32(Math.Floor(hue / 60)) % 6;
double f = hue / 60 - Math.Floor(hue / 60);
value = value * 255;
int v = Convert.ToInt32(value);
int p = Convert.ToInt32(value * (1 - saturation));
int q = Convert.ToInt32(value * (1 - f * saturation));
int t = Convert.ToInt32(value * (1 - (1 - f) * saturation));
if (hi == 0)
return Color.FromArgb(255, v, t, p);
else if (hi == 1)
return Color.FromArgb(255, q, v, p);
else if (hi == 2)
return Color.FromArgb(255, p, v, t);
else if (hi == 3)
return Color.FromArgb(255, p, q, v);
else if (hi == 4)
return Color.FromArgb(255, t, p, v);
else
return Color.FromArgb(255, v, p, q);
}
public void convertToHSV(Color color, out double hue, out double saturation, out double value)
{
int max = Math.Max(color.R, Math.Max(color.G, color.B));
int min = Math.Min(color.R, Math.Min(color.G, color.B));
hue = color.GetHue();
saturation = (max == 0) ? 0 : 1d - (1d * min / max);
value = max / 255d;
}
Regarding
int hi = Convert.ToInt32(Math.Floor(hue / 60)) % 6;
Hue might be represented as larger than 360 or smaller than 0, if there are color transformations involved in other pieces of code that do not make sure to divide mod 360.
If you are 100% sure that all other functions are going to return Hue within [0,360] then the modulo 6 is not needed.
In HSV, Value is typically normalized to the [0,1] continuous interval, whereas in RGB in the discrete [0,255] interval. Hence both:
value = value * 255;
and
value = max / 255d;

Calculating bearing between two CLLocationCoordinate2Ds

Very "simple" problem: given two CLLocationCoordinate2Ds, how can I get the bearing (as radians) from the first to the second? I've done a lot of research and studying on this, both the general problem and Objective-C/Cocoa Touch/iOS specifically.
Here's my implementation:
- (float) getHeadingForDirectionFromCoordinate:(CLLocationCoordinate2D)fromLoc toCoordinate:(CLLocationCoordinate2D)toLoc
{
float fLat = fromLoc.latitude;
float fLng = fromLoc.longitude;
float tLat = toLoc.latitude;
float tLng = toLoc.longitude;
return atan2(sin(fLng-tLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(fLng-tLng));
}
However, this method isn't returning consistant results for me. If the bearing is close to due north or due south, it seems to be fine, however, any other direction seems to return inconsistant data, for example:
From 50.405018, 8.437500
To 51.339802, 12.403340
My method returns: 5.918441 radians
Should be 1.18660576 radians
(see http://www.movable-type.co.uk/scripts/latlong.html and http://www.movable-type.co.uk/scripts/latlong-map.html?lat1=50.405018&long1=8.437500&lat2=51.339802&long2=12.403340)
I've double and triple checked the formula is correct. I've also spot checked a bunch of values like the example above, some correct, some wrong. I've played around with various modulos or bounding of the return value, also no luck.
Any ideas? Is there an issue with my code? Maybe I've misunderstood something about how math functions work?
Here the code modified with the changes suggested by Oren Trutner and from myself:
#define degreesToRadians(x) (M_PI * x / 180.0)
#define radiansToDegrees(x) (x * 180.0 / M_PI)
- (float)getHeadingForDirectionFromCoordinate:(CLLocationCoordinate2D)fromLoc toCoordinate:(CLLocationCoordinate2D)toLoc
{
float fLat = degreesToRadians(fromLoc.latitude);
float fLng = degreesToRadians(fromLoc.longitude);
float tLat = degreesToRadians(toLoc.latitude);
float tLng = degreesToRadians(toLoc.longitude);
float degree = radiansToDegrees(atan2(sin(tLng-fLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng)));
if (degree >= 0) {
return degree;
} else {
return 360+degree;
}
}
Your math is correct, with the following exceptions:
Make sure to convert fLat, fLon, tLat, and tLon to radians before applying any sin() or cos() to them. Divide by 180.0 and multiply by PI.
Enter the delta between tLng and fLng as tLng-fLng, and not the other way around. Note that this difference appears twice in the expression.
With those changes, I am getting 1.18660677830947 radians with double precision math and the values in the question.
Swift 3:
extension CLLocationCoordinate2D {
func bearing(to point: CLLocationCoordinate2D) -> Double {
func degreesToRadians(_ degrees: Double) -> Double { return degrees * Double.pi / 180.0 }
func radiansToDegrees(_ radians: Double) -> Double { return radians * 180.0 / Double.pi }
let lat1 = degreesToRadians(latitude)
let lon1 = degreesToRadians(longitude)
let lat2 = degreesToRadians(point.latitude);
let lon2 = degreesToRadians(point.longitude);
let dLon = lon2 - lon1;
let y = sin(dLon) * cos(lat2);
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
let radiansBearing = atan2(y, x);
return radiansToDegrees(radiansBearing)
}
}
you can use my code.. it's work on my project with microcontroller that use GPS for data.
#define d2r ((22/7.0)/180.0)
#define r2d (180.0/(22/7.0))
double get_heading1(double lat1, double long1, double lat2, double long2)
{
double diff_lat, diff_long;
double degree;
diff_long =(double) (((long2*1000000)-(long1*1000000))/1000000) * d2r;
diff_lat = (double) (((lat2*1000000)-(lat1*1000000))/1000000) * d2r;
degree = r2d (atan2(sin(diff_long)*cos(d2r*lat2),cos(d2r*lat1)*sin(d2r*lat2)-sin(d2r*lat1)*cos(d2r*lat2) *cos(diff_long)));
if (degree >= 0) {
return degree;
} else {
return 360+degree;
}
}

Resources