>> x = 14.021
>> num2str(x,'%4.5f')
I want to get this as a result:
0014.02100
But, MATLAB just answers me with:
14.02100
You should use sprintf. For example:
x = 14.021
sprintf('%010.5f', x)
Note that you don't need to use num2str.
The first argument to sprintf is the format specifier which describes how the resulting text should be displayed. The specifier begins with %, the leading 0 tells sprintf to pad the string with zeros. Loosely, the .5 tells it to print five digits to the right of decimal point and the f tells it we want to format it like a floating point number.
Related
I am writing code where I would like the user to enter the desire decimal point precision. For example:
for x in numbers:
print "{:10.*f}".format(x)
...except where the '*' is I would like to place a variable that which the user provided value. My search for a solution in available documentation has proved unfruitful.
How about print '{:10.{precision}f}'.format(x, precision=precision), where precision is a value defined elsewhere?
Python One-liner
number = 10.123456789
print ('{:10.{precision}f}'.format(number, precision=int(input("Enter the precision"))))
Output :
>>> print ('{:10.{precision}f}'.format(number, precision=int(input("Enter the precision\n"))))
Enter the precision
5
10.12346
Try this in Matlab R2015b:
>> sprintf('%i\n',uint64(2)^62)
ans =
4611686018427387904 %// correct
>> sprintf('%i\n',uint64(2)^63)
ans =
9.223372e+18 %// why scientific notation?
In R2010b it's worse: a number as low as uint64(2)^31 already causes this behaviour:
>> sprintf('%i\n',uint64(2)^31)
ans =
2.147484e+009
Why does sprintf use scientific notation with the '%i' or '%d' format specifiers? Can this be avoided?
Using num2str instead of sprintf is not a solution for me. Even though it does avoid scientific notation,
>> num2str(uint64(2)^63)
ans =
9223372036854775808 %// correct
I need to use sprintf because num2str doesn't support the "leading spaces" format specifier:
>> sprintf('% 25i\n',uint64(2)^62, uint64(2)^50)
ans =
4611686018427387904
1125899906842624 %// correct: leading spaces to give 25 characters for each number
>> num2str([uint64(2)^62;uint64(2)^50], '% 25i\n')
ans =
4611686018427387904
1125899906842624 %// incorrect: no leading spaces
>> num2str(uint64(2)^50, '% 25i\n')
ans =
1125899906842624 %// incorrect: no leading spaces
Looking at this question, it seems that MATLAB, for some reason (possibly because it's expecting a signed integer from %i but you're giving it an unsigned one), treats the very-big-number (2^63) as a float, and converts it to scientific notation which is also why if you write sprintf('%.18i\n',bitshift(uint64(2),62)) you end up losing precision:
9.223372036854775800e+18 vs. 9223372036854775808
Using %u as opposed to %i seems to produce the correct result:
sprintf('%u\n',bitshift(uint64(2),62))
ans =
9223372036854775808
(It makes more sense to use bitshift in this specific scenario)
I'm just playing around with Lua trying to make a calculator that uses string manipulation. Basically I take two numbers out of a string, then do something to them (+ - * /). I can successfully take a number out of x, but taking a number out of y always returns nil. Can anyone help?
local x = "5 * 75"
function calculate(s)
local x, y =
tonumber(s:sub(1, string.find(s," ")-1)),
tonumber(s:sub(string.find(s," ")+3), string.len(s))
return x * y
end
print(calculate(x))
You have a simple misplaced parenthesis, sending string.len to tonumber instead of sub.
local x, y =
tonumber(s:sub(1, string.find(s," ")-1)),
tonumber(s:sub(string.find(s," ")+3, string.len(s)))
You actually don't need the string.len, as end of string is the default value for sub if nothing is given.
EDIT:
You can actually do what you want to do way shorter by using string.match instead.
local x,y = string.match(s,"(%d+).-(%d+)")
Match looks for tries to match the string with the pattern given and returns the captured values, in this case the numbers. This pattern translates to "One or more digits, then as few as possible of any character, then one or more digits". %d is 1 digit, + means one or more. . means any character and - means as few as possible. The values within the parentheses are captured, which means that they are returned.
I have a double value. I want to format this value in the format of x.yz. How do I do this? I keep getting digits truncated. Can someone tell me how to do this in C#?
Thanks!
Digits after decimal point
This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.
// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"
Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.
// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"
Digits before decimal point
If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.
// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567); // "123.5"
String.Format("{0:00.0}", 23.4567); // "23.5"
String.Format("{0:00.0}", 3.4567); // "03.5"
String.Format("{0:00.0}", -3.4567); // "-03.5"
Thousands separator
To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.
String.Format("{0:0,0.0}", 12345.67); // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"
Zero
Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).
Following code shows how can be formatted a zero (of double type).
String.Format("{0:0.0}", 0.0); // "0.0"
String.Format("{0:0.#}", 0.0); // "0"
String.Format("{0:#.0}", 0.0); // ".0"
String.Format("{0:#.#}", 0.0); // ""
Align numbers with spaces
To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.
String.Format("{0,10:0.0}", 123.4567); // " 123.5"
String.Format("{0,-10:0.0}", 123.4567); // "123.5 "
String.Format("{0,10:0.0}", -123.4567); // " -123.5"
String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "
Custom formatting for negative numbers and zero
If you need to use custom format for negative float numbers or zero, use semicolon separator „;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.
String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"
http://www.csharp-examples.net/string-format-double/
Using format strings is explained in:
Standard Numeric Format Strings
Custom Numeric Format Strings
For example, try:
(0.56789).ToString("F2")
(0.56789).ToString("0.00").
Note that the resulting value is NOT truncated, but rounded in both cases, resulting in "0.57".
string.Format("{0:0.00}",yourdouble);
And maybe you'll find useful stick a paper with this http://john-sheehan.com/blog/wp-content/uploads/msnet-formatting-strings.pdf somewhere in your office
Tried something like this, using ToString?
doubleNumber = -1898300.1937;
Console.WriteLine(doubleNumber.ToString("F2", CultureInfo.InvariantCulture));
// Displays -1898300.19
I'm using Math.Round Method
Math.Round(yourdouble, 2)
You can also specify the rounding rule.
Try this:
number.ToString("0.00");
Also take a look at Custom Numeric Format Strings
I have a line like this:
pad (2) = 0x0041
I wanna change the hex into decimal and the expected result is
pad (2) = 65
I just tried :%s/\(.*\) = \(.*\)/\1 = \=printf("%d", submatch(2)), but it failed.
Would you help to solve this?
Vim has a str2nr() function to convert different number representations to their decimal values. To convert hex values you could use it like this:
s/0x[0-9a-fA-F]\+/\=str2nr(submatch(0), 16)
Your code is almost ok, but, according to the documentation:
When the substitute string starts with "\=" the remainder is interpreted as an
expression. This does not work recursively: a substitute() function inside
the expression cannot use "\=" for the substitute string.
So, you may change your code to
%s/\(.*\) = \(.*\)/\=submatch(1)." = ".printf("%d", submatch(2))