Better way to combine number with fraction?
1 次查看(过去 30 天)
显示 更早的评论
I have this struct output (from ROS2 message):
MessageType: 'builtin_interfaces/Time'
sec: 1706819594
nanosec: 685974901
I want to combine sec and nanosec in one value like this:
1706819594.685974901
I used the following line of code (and it worked):
zBase.header.stamp.sec+ sprintf(".%d",zBase.header.stamp.nanosec)
Is there a better way ?
0 个评论
采纳的回答
Stephen23
2024-2-1
编辑:Stephen23
2024-2-1
Note that you will need to use SPRINTF (or COMPOSE etc) to get the right output when NANOSEC has fewer than the full nine digits:
s = 1706819594;
ns = 685974901;
sprintf("%d.%09d",s,ns)
ns = 123;
sprintf("%d.%09d",s,ns)
Whereas your format string will given an incorrect output:
s + sprintf(".%d",ns)
If the input number has more than nine digits then the output will be wrong anyway.
5 个评论
Stephen23
2024-2-3
If the two values are numeric and you want a single numeric output then skip the intermediate text:
format long G
s = 1706819594;
ns = 685974901;
out = s + ns/1e9
As mentioned elsewhere in this thread, converting to numeric will irretrievably lose information.
更多回答(1 个)
Jon
2024-2-1
If you want to use it as a numerical value I would do this
val = str2double(zBase.header.stamp.sec) + str2double(zBase.header.stamp.nanosec)/1e9
4 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Publishers and Subscribers 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!