Numbers Fractionate - flutter

can you ask me a question? I have several double that receive a value of a calculation but would like to know how I can fractionate these values received? In the case would be: 13.232 to 13.23 ..
Code:
Future calculate() {
double precototal1 =
double.parse(_precoCtrl.text.replaceAll(new RegExp(r'[,.]'), '')) * 12;
double precototal2 =
double.parse(_precoCtrl1.text.replaceAll(new RegExp(r'[,.]'), '')) * 12;
double unidademl1 =
double.parse(_unitCtrl.text.replaceAll(new RegExp(r'[,.]'), ''));
double unidademl2 =
double.parse(_unitCtrl1.text.replaceAll(new RegExp(r'[,.]'), ''));
double difvalor = 0;
double latas = 0;
double litros = 0;
double totlitros = 0;
double diflitros = 0;
setState(() {
_completed = false;
_busy = true;
});
return new Future.delayed(const Duration(seconds: 1), () {
setState(
() {
print(formatter.format(precototal2));
if (precototal1 > precototal2) {
difvalor = precototal1 - precototal2;
latas = (difvalor / precototal2);
litros = (latas * unidademl2);
totlitros = litros + unidademl2;
diflitros = (totlitros - unidademl1);
} else {
difvalor = (precototal2 - precototal1);
latas = (difvalor + precototal1);
totlitros = litros + unidademl1;
litros = (latas / unidademl1);
diflitros = (unidademl2 - totlitros);
}

Use the toStringAsFixed method.
Example:
double value = 15.2235;
String fmtValue = value.toStringAsFixed(2);

Related

error: Conditions must have a static type of 'bool'

I tried to make a calculator in flutter for the first time, but an error occur at the bool type that i don't understand. (on the "if" opertaion)
class _CalculatorAppState extends State<CalculatorApp> {
int? firstNum;
int? secondnum;
String? textToDisplay;
String? history = '';
String? res = '';
String? operation;
void btnOnClick(String btnVal){
print(btnVal);
if( btnVal == 'C'){
textToDisplay = '';
firstNum = 0;
secondnum = 0;
res= '';
} else if (btnVal == 'C'){
textToDisplay = '';
firstNum = 0;
secondnum = 0;
res= '';
history = '';
} else if ( btnVal == '+'||
btnVal == '-'||
btnVal == '/'||
btnVal == 'X') {
firstNum = int.parse(textToDisplay!);
res = '';
operation = btnVal;
} else if (btnVal == '='){
secondnum = int.parse(textToDisplay!);
if(operation = '+') {
res = (firstNum! + secondnum!).toString();
history = firstNum.toString() + operation.toString() + secondnum.toString();
}
if(operation = '-') {
res = (firstNum! - secondnum!).toString();
history = firstNum.toString() + operation.toString() + secondnum.toString();
}
if(operation = 'X') {
res = (firstNum! * secondnum!).toString();
history = firstNum.toString() + operation.toString() + secondnum.toString();
}
if(operation = '/') {
res = (firstNum! / secondnum!).toString();
history = firstNum.toString() + operation.toString() + secondnum.toString();
} else {
res = int.parse(textToDisplay! + btnVal).toString();
}
setState(() {
textToDisplay = res;
});
}
}
error: Conditions must have a static type of 'bool'. (non_bool_condition at [calculator] lib\main.dart:46)
error: Conditions must have a static type of 'bool'. (non_bool_condition at [calculator] lib\main.dart:50)
error: Conditions must have a static type of 'bool'. (non_bool_condition at [calculator] lib\main.dart:54)
error: Conditions must have a static type of 'bool'. (non_bool_condition at [calculator] lib\main.dart:58)
You're currently typing operation = 'x' which isnt valid syntax. You need a double '=', so:
if (operation == 'x') {
// do stuff
}
The equality operator is == not =.
At those lines listed you used = instead of ==.
And declare the variables as follows:
var firstNum = 0;
var secondnum = 0;
var textToDisplay = '';
var history = '';
var res = '';
var operation = '';

In Flutter and if the number after decimal point is equal 0 convert the number to int

This is a function if the endValueFixed is equal for example 12.0 I want to print the number without zero so I want it to be 12.
void calculateIncrease() {
setState(() {
primerResult = (startingValue * percentage) / 100;
endValue = startingValue + primerResult;
endValueFixe`enter code here`d = roundDouble(endValue, 2);
});
}
This may be an overkill but it works exactly as you wish:
void main() {
// This is your double value
final end = 98.04;
String intPart = "";
String doublePart = "";
int j = 0;
for (int i = 0; i < end.toString().length; i++) {
if (end.toString()[i] != '.') {
intPart += end.toString()[i];
} else {
j = i + 1;
break;
}
}
for (int l = j; l < end.toString().length; l++) {
doublePart += end.toString()[l];
}
if (doublePart[0] == "0" && doublePart[1] != "0") {
print(end);
} else {
print(end.toString());
}
}
You may use this code as a function and send whatever value to end.
if (endValueFixed==12) {
print('${endValueFixed.toInt()}');
}
conditionally cast it to an int and print it then :)

How to change the audio sample rate in Unity?

The default audio sample rate is 48000. Is it possible to change it to other values like 44100?
I log the value of AudioSettings.outputSampleRate and it shows 48000. But it doesn't seem possible to change that value.
Here is the code to change sample rate of Unity's AudioClip:
Most simple, but very rough
Averaging approach, but channels are get mixed
Averaging approach for each channel (best quality)
public static AudioClip SetSampleRateSimple(AudioClip clip, int frequency)
{
if (clip.frequency == frequency) return clip;
var samples = new float[clip.samples * clip.channels];
clip.GetData(samples, 0);
var samplesLength = (int)(frequency * clip.length) * clip.channels;
var samplesNew = new float[samplesLength];
var clipNew = AudioClip.Create(clip.name + "_" + frequency, samplesLength, clip.channels, frequency, false);
for (var i = 0; i < samplesLength; i++)
{
var index = (int) ((float) i * samples.Length / samplesLength);
samplesNew[i] = samples[index];
}
clipNew.SetData(samplesNew, 0);
return clipNew;
}
public static AudioClip SetSampleRateAverage(AudioClip clip, int frequency)
{
if (clip.frequency == frequency) return clip;
var samples = new float[clip.samples * clip.channels];
clip.GetData(samples, 0);
var samplesNewLength = (int) (frequency * clip.length) * clip.channels;
var samplesNew = new float[samplesNewLength];
var clipNew = AudioClip.Create(clip.name + "_" + frequency, samplesNewLength, clip.channels, frequency, false);
var index = 0;
var sum = 0f;
var count = 0;
for (var i = 0; i < samples.Length; i++)
{
var index_ = (int)((float)i / samples.Length * samplesNewLength);
if (index_ == index)
{
sum += samples[i];
count++;
}
else
{
samplesNew[index] = sum / count;
index = index_;
sum = samples[i];
count = 1;
}
}
clipNew.SetData(samplesNew, 0);
return clipNew;
}
public static AudioClip SetSampleRate(AudioClip clip, int frequency)
{
if (clip.frequency == frequency) return clip;
if (clip.channels != 1 && clip.channels != 2) return clip;
var samples = new float[clip.samples * clip.channels];
clip.GetData(samples, 0);
var samplesNewLength = (int) (frequency * clip.length) * clip.channels;
var clipNew = AudioClip.Create(clip.name + "_" + frequency, samplesNewLength, clip.channels, frequency, false);
var channelsOriginal = new List<float[]>();
var channelsNew = new List<float[]>();
if (clip.channels == 1)
{
channelsOriginal.Add(samples);
channelsNew.Add(new float[(int) (frequency * clip.length)]);
}
else
{
channelsOriginal.Add(new float[clip.samples]);
channelsOriginal.Add(new float[clip.samples]);
channelsNew.Add(new float[(int) (frequency * clip.length)]);
channelsNew.Add(new float[(int) (frequency * clip.length)]);
for (var i = 0; i < samples.Length; i++)
{
channelsOriginal[i % 2][i / 2] = samples[i];
}
}
for (var c = 0; c < clip.channels; c++)
{
var index = 0;
var sum = 0f;
var count = 0;
var channelSamples = channelsOriginal[c];
for (var i = 0; i < channelSamples.Length; i++)
{
var index_ = (int) ((float) i / channelSamples.Length * channelsNew[c].Length);
if (index_ == index)
{
sum += channelSamples[i];
count++;
}
else
{
channelsNew[c][index] = sum / count;
index = index_;
sum = channelSamples[i];
count = 1;
}
}
}
float[] samplesNew;
if (clip.channels == 1)
{
samplesNew = channelsNew[0];
}
else
{
samplesNew = new float[channelsNew[0].Length + channelsNew[1].Length];
for (var i = 0; i < samplesNew.Length; i++)
{
samplesNew[i] = channelsNew[i % 2][i / 2];
}
}
clipNew.SetData(samplesNew, 0);
return clipNew;
}

Trouble looping and remove createjs "on" eventListener with "off"

Im trying to loop and remove eventlistener in createjs:
Actor = function() {
this.update = true;
this.offset;
this.instance;
this.member = function(a_obj) {
count++;
this._container = a_obj.container;
this._images = a_obj.images;
this._name = a_obj.name;
this._top = a_obj.top;
this._left = a_obj.left;
getCirTest = new createjs.Bitmap(loader.getResult(this._images));
getCirTest.name = this._name;
getCirTest.y = this._top + 10;
getCirTest.x = this._left + 10;
getCirTest.scaleX = 0.8;
getCirTest.scaleY = 0.8;
getCirTest.cursor = "pointer";
this._container.addChild(getCirTest);
holdsAllObj[count]=getCirTest;
console.log(holdsAllObj);
md = getCirTest.on("mousedown", activate);
function activate(evt) {
myCurrentTarget = evt.currentTarget;
xyCor.push(evt.currentTarget.x, evt.currentTarget.y);
this.parent.addChild(this);
this.offset = {
x: this.x - evt.stageX,
y: this.y - evt.stageY
};
}
pm = getCirTest.on("pressmove", move);
function move(evt) {
myintersect(evt.currentTarget, getCenterBitmap);
this.x = evt.stageX + this.offset.x;
this.y = evt.stageY + this.offset.y;
update = true;
}
cc = getCirTest.on("click", release);
function release (evt) {
countClicks++;
holdsAllObj[1].off("mousedown",md);
holdsAllObj[1].off("pressmove",pm);
console.log();
if (soundPlay == true && countClicks == 1) {
console.log("im true");
mySoundInstance = createjs.Sound.play(evt.currentTarget.name);
mySoundInstance.addEventListener("complete", createjs.proxy(handleSoundComplete, mySoundInstance));
} else {
createjs.Sound.stop(evt.currentTarget.name);
countClicks = 0;
}
console.log(countClicks);
update = true;
}
} //**** END: members ****
}
Its my getCirTest, whichs have an event:
md = getCirTest.on("mousedown", activate);
It´s create 10 instance of a bitmap object like this:
for (var circles = 0; circles < 10; circles++) {
var x = Math.round(container.width / 2 + radius * Math.cos(angle) - 150 / 2);
var y = Math.round(container.width / 2 + radius * Math.sin(angle) - 150 / 2);
var MP = new Actor();
MP.member({
container: container,
images: myFTMImages[circles],
name: myFTMNames[circles],
top: y,
left: x
});
angle += step;
}
My problem is that i would like to remove the eventListeners in a event:
cc = getCirTest.on("click", release);
function release (evt) {
}
Thats why i have put the bitmaps in a array:
holdsAllObj[count]=getCirTest;
And then tried the following:
cc = getCirTest.on("click", release);
function release (evt) {
for(var ijk=0;ijk<holdsAllObj.length;ijk++){
holdsAllObj[ijk].off("mousedown",md);
holdsAllObj[ijk].off("pressmove",pm);
}
}
unfortunately .. it´does not work for me ...
This looks like an issue with js scope. JS methods are called in the window context rather than the context they are created. You can use the createjs.proxy method to apply a scope to a method call, like this:
cc = getCirTest.on("click", release, this);
Hope that helps.

coffeescript strange behavior in subtraction

I must be going crazy. Coffeescript is continualy returning '0' for the difference between two non-equal integers.
x = #location[0]
y = #start[0]
console.log "#{x} - #{y} = #{x-y}"
This is outputting:
350 - 322 = 0
250 - 278 = 0
... and so on
I'm completely confused!
Edit: Here's the source in both coffee and the compiled js
class Branch
constructor: (#length, #start, #angle, #generation, #parent) ->
return if #generation >= RECURSION_LIMIT
#angleVariation = pi/3
#ratio = 2/(1+root(5))
#maxChildren = 10
#parent ?= null
#unit = 2
#children = []
#location = #start
#childLocations = [Math.random()*#length*#ratio/2+(#length*#ratio) \
for n in [0...#maxChildren]]
grow: ->
gl.beginPath()
moveTo #location
#location[0] += #unit * cos(#angle)
#location[1] -= #unit * sin(#angle)
lineTo #location
gl.stroke()
console.log #getLength()
if #getLength() >= #childLocations[#children.length]
#birthChild()
getLength: ->
x = #location[1]
y = #start[1]
console.log "#{x} - #{y} = #{x-y}"
return 1 #root( (#location[0]-#start[0])**2 + (#location[1]-#start[1])**2 )
birthChild: ->
angle = #angle + (Math.random()*#angleVariation*2) - #angleVariation
child = new Branch #length * #ratio, #location, angle, #generation+1, this
And in js:
Branch = (function() {
function Branch(length, start, angle, generation, parent) {
var n, _ref;
this.length = length;
this.start = start;
this.angle = angle;
this.generation = generation;
this.parent = parent;
if (this.generation >= RECURSION_LIMIT) {
return;
}
this.angleVariation = pi / 3;
this.ratio = 2 / (1 + root(5));
this.maxChildren = 10;
if ((_ref = this.parent) == null) {
this.parent = null;
}
this.unit = 2;
this.children = [];
this.location = this.start;
this.childLocations = [
(function() {
var _i, _ref1, _results;
_results = [];
for (n = _i = 0, _ref1 = this.maxChildren; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; n = 0 <= _ref1 ? ++_i : --_i) {
_results.push(Math.random() * this.length * this.ratio / 2 + (this.length * this.ratio));
}
return _results;
}).call(this)
];
}
Branch.prototype.grow = function() {
gl.beginPath();
moveTo(this.location);
this.location[0] += this.unit * cos(this.angle);
this.location[1] -= this.unit * sin(this.angle);
lineTo(this.location);
gl.stroke();
console.log(this.getLength());
if (this.getLength() >= this.childLocations[this.children.length]) {
return this.birthChild();
}
};
Branch.prototype.getLength = function() {
var x, y;
x = this.location[1];
y = this.start[1];
console.log("" + x + " - " + y + " = " + (x - y));
return 1;
};
Branch.prototype.birthChild = function() {
var angle, child;
angle = this.angle + (Math.random() * this.angleVariation * 2) - this.angleVariation;
return child = new Branch(this.length * this.ratio, this.location, angle, this.generation + 1, this);
};
return Branch;
})();