简体   繁体   中英

How to round decimal values with bash script?

After running some code, i did get this 4D-array which i saved in a txt file, the values are quite long so i need to round them to 6 decimal places, the changes should be done in the original file, so i can have the same format of the array not just printing the values

here a part of the array

[[[[-0.027340000495314598, -0.07065500319004059, 0.06236099824309349, -0.11684399843215942, -0.05784200131893158], [-0.16122999787330627, -0.14122700691223145, -0.1653739959001541, 0.1630070060491562, 0.05366099998354912], [0.035610001534223557, -0.05879399925470352, 0.06178700178861618, 0.15509599447250366, -0.11066299676895142], [-0.006271999794989824, -0.04911699891090393, -0.06760299950838089, -0.005801999941468239, 0.02808699943125248], [-0.1022690013051033, -0.08862099796533585, 0.14321200549602509, -0.00038400001358240843, 0.10744699835777283]]
$ echo '[[[[-0.027340000495314598, -0.07065500319004059, 0.06236099824309349' |
    perl -pe 's/([-+]?[0-9]*\.[0-9]+|[0-9]+)/sprintf "%.6f","$1"/ge'
[[[[-0.027340, -0.070655, 0.062361

You can use printf for this. I found an example here

printf "%.*f\n" 6 "-0.027340000495314598"

will return -0.027340. 6 represents the number of digits to print

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM