How to format a float without trailing zeros in Rust? - rust

I'm formatting f64 like this:
format!("{:.8}", x)
This returns strings like this:
110.00000000
601.47000000
4.50000000
I'm looking to remove all the extra zeros at the end of each so that the output is this:
110
601.47
4.5
I'm hoping to do this without any external crates or libraries (not a big deal if it has to happen though). Is there something built-in to Rust that can accomplish this? Or will I have to write a custom function to do so?
Edit:
I should add that I can't simple do format("{}", x) because that will return strings like this:
40.019999999999996
1192.6499999999999
2733.9599999999996
Is there a way around that?

This currently solves the issue for me:
let y = (x * 100_000_000.0).round() / 100_000_000.0;
format!("{}", y);
I will keep an eye out for any better solutions. Thank you!

You can just do
format!("{}", x)
The {:.8} requires 8 places of precision, and thus, prints out extra zeros to that precision.

Related

Julia: Modifying the same field in an array of Mutable Structs

I am looking for the best way to adjust the same field, y, of an array of mutable structs, x to the same number.
x[:].y=0 kind of thing. In matlab I've seen it done using the deal() function. How can I do this in Julia?
You can use broadcasting:
setproperty!.(x, :y, 0)
Don't be afraid of writing the most obvious thing: a loop! It will be efficient in Julia. For example something like
for el in x
el.y = 0
end

How to convert a string into a variable name in MATLAB? [duplicate]

Let's assume that I want to create 10 variables which would look like this:
x1 = 1;
x2 = 2;
x3 = 3;
x4 = 4;
.
.
xi = i;
This is a simplified version of what I'm intending to do. Basically I just want so save code lines by creating these variables in an automated way. Is there the possibility to construct a variable name in Matlab? The pattern in my example would be ["x", num2str(i)]. But I cant find a way to create a variable with that name.
You can do it with eval but you really should not
eval(['x', num2str(i), ' = ', num2str(i)]); %//Not recommended
Rather use a cell array:
x{i} = i
I also strongly advise using a cell array or a struct for such cases. I think it will even give you some performance boost.
If you really need to do so Dan told how to. But I would also like to point to the genvarname function. It will make sure your string is a valid variable name.
EDIT: genvarname is part of core matlab and not of the statistics toolbox
for k=1:10
assignin('base', ['x' num2str(k)], k)
end
Although it is long overdue, i justed wanted to add another answer.
the function genvarname is exactly for these cases
and if you use it with a tmp structure array you do not need the eval cmd
the example 4 from this link is how to do it http://www.mathworks.co.uk/help/matlab/ref/genvarname.html
for k = 1:5
t = clock;
pause(uint8(rand * 10));
v = genvarname('time_elapsed', who);
eval([v ' = etime(clock,t)'])
end
all the best
eyal
If anyone else is interested, the correct syntax from Dan's answer would be:
eval(['x', num2str(i), ' = ', num2str(i)]);
My question already contained the wrong syntax, so it's my fault.
I needed something like this since you cannot reference structs (or cell arrays I presume) from workspace in Simulink blocks if you want to be able to change them during the simulation.
Anyway, for me this worked best
assignin('base',['string' 'parts'],values);

How to convert a number to string in coffeescript?

Given a number
n = 42
What is the best way to convert it into a string?
s = String(n)
or
s = ''+n
or any better suggestion?
String interpolation might be the most natural approach in CoffeeScript:
s = "#{n}" # Just `'' + n` in disguise.
That might leave people wondering what you're doing though.
I think the best way would be:
(10).toString()
// or
n = 11;
n.toString()
Edited to fix syntax error. 10.toString() works in the CoffeeScript simulator but it's better to be safe.
There is no solution that is more "natural" than the other. Both are explicit and the reader will understand what it does right away in both cases.
Concerning performance, from this test, the fastest is :
s = '' + n
The other method, String(n), is slower.

Modulus/Remainder function for non-integers

rem gives this:
Prelude> rem 9 8
1
I wanted something like this:
Prelude> nonIntRem 9.1 8
1.0999999999999996
I implemented it like this:
nonIntRem x y = x - (y * (fromIntegral $ truncate (x/y)))
My questions are:
Does something like this already exist in a standard Haskell library? I'd prefer to use a standard function, and I may have missed it.
If not, is there a more standard name for this function in other languages? Maybe fmod, but the behavior for negatives in this case is not like mod, but like rem. If there is no standard name, can you think of a better name for this function?
It seems to work properly, but if you notice a problem with this function, I'd like to know about it.
The function you're after is mod' from Data.Fixed.

Find all possible variations of a string of letters

Newb programmer here, I'm most familiar with Python but also learning C and Java, so either of 3 would be fine.
What I have is a string of letters, say:
ABXDEYGH
However say,
X is possible to be M and N.
Y is possible to be P and Q.
In this example, I would like basically to print all possible variations of this string of letters.
Like:
ABMDEPGH
ABNDEPGH
ABMDEQGH
ABNDEQGH
Any help would be appreciated. Thanks in advance
This boils down to a simple problem of permutations. What you care about is the part of the text that can change; the variables. The rest can be ignored, until you want to display it.
So your question can be more simply stated: What are all the possible permutations of 1 item from set X and another item from set Y? This is known as a cross-product, sometimes also simply called a product.
Here's a possible Python solution:
import itertools
x = set(['M', 'N'])
y = set(['P', 'Q'])
for items in itertools.product(x, y)
print 'AB{0}DE{1}GH'.format(*items)
Note that the print ''.format() command uses the "unpack arguments" notation described here.
why dont you write two loops. one to replace all possible characters with X and one for Y.
foreach(char c in charSet1){
// replaces X
foreach(char ch in charSet2){
// replace Y
}
}

Resources