So this maybe an easy question. I have some incoming decimal .12345 and I want to make that 12345. Now this value can change so I dont want to just multiply it by 100,000. For example if the incoming value was .123 I want 123, If it was .3219 I want 3219.
Asked
Active
Viewed 664 times
4
-
3But it won't be 0.123 because of floating point math. 0.123 is stored as 0.1229999999999999982236431605997495353221893310546875 in IEEE 754 float in your computer. So you need to round to a level – Ander Biguri Feb 15 '18 at 19:30
-
2Is your "incoming decimal" being read from a text file or the like (i.e. is it a character string)? – gnovice Feb 15 '18 at 19:32
-
And if the "incoming value" is `.1230` I suppose you want something different from when it is `.123` ? – Ben Voigt Feb 15 '18 at 22:07
1 Answers
7
here's something to play with: (assuming your input is a number (double or single)
f=@(x) x*10^sum(floor(x*10.^[0:16])~=x*10.^[0:16])
this assumes a floating point accuracy of up to 16 digits...
try f(.123)
...
an additional note, the output will look like an integer but it really is still a double\single. In order to really make it to an integer class one you'll need to cast with uint64(f(x))
or whatever integer type you need.
Another solution is to cast to string using num2str, take out the 0. and cast back to num using str2num:
f=@(x) str2num(subsref(num2str(x),struct('type','()','subs',{{1,3:numel(num2str(x))}})));
ugly but works...

bla
- 25,846
- 10
- 70
- 101